Search code examples
c#filestream

FileStream and creating folders


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.


Solution

  • 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.)