open - save file with current date and time c#




How to create a directory using StreamWriter? (3)

Is it possible to create a directory using StreamWriter?


Have you tried not using File.Create()? like so:

using (StreamWriter stream = new StreamWriter(filePath)) {
    stream.Write(data);
    stream.Close();
}

No. You can't actually create a directory using a StreamWriter. Use Directory.CreateDirectory instead.

If you're trying to read the directory name out of a file stream and then create a file based on that text, you'll need something like this:

FileStream fs; // this is the filestream from somewhere. make sure to dispose it
using (StreamReader r = new StreamReader(fs))
    Directory.CreateDirectory(r.ReadToEnd());

StreamWriter doesn't write to a file that doesn't exist

You're missing a constructor which takes a boolean that can aid in creating the file:

using (StreamWriter stream = new StreamWriter(filePath, false)) {
    stream.Write(data);
    stream.Close();
}

The logic is actually is little more complex than that, however:

public StreamWriter( string path, bool append )

Determines whether data is to be appended to the file. If the file exists and append is false, the file is overwritten. If the file exists and append is true, the data is appended to the file. Otherwise, a new file is created.