Just a quick question. I'm using something like this
FileStream fs = new FileStream(fileName, FileMode.Create);
I was wondering whether there was a parameter I could pass to it to force it to create the folder if it doesn't exist. At the moment an exception is throw if folder isn't found.
If there is a better method then using FileStream
I'm open to ideas.
Remarks. Use the FileStream class to read from, write to, open, and close files on a file system, and to manipulate other file-related operating system handles, including pipes, standard input, and standard output.
This task can be accomplished by using the mkdir() function. Directories are created with this function. (There is also a shell command mkdir which does the same thing). The mkdir() function creates a new, empty directory with name filename.
The FileStream is a class used for reading and writing files in C#. It is part of the System.IO namespace. To manipulate files using FileStream, you need to create an object of FileStream class. This object has four parameters; the Name of the File, FileMode, FileAccess, and FileShare.
Use Directory.CreateDirectory:
Directory.CreateDirectory Method (String)
Creates all directories and subdirectories as specified by path.
Example:
string fileName = @"C:\Users\SomeUser\My Documents\Foo\Bar\Baz\text1.txt"; Directory.CreateDirectory(Path.GetDirectoryName(fileName)); using (FileStream fs = new FileStream(fileName, FileMode.Create)) { // ... }
(Path.GetDirectoryName returns the directory part of the file name.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With