65

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.

John Saunders
  • 157,405
  • 24
  • 229
  • 388
Ash Burlaczenko
  • 21,581
  • 14
  • 63
  • 95

2 Answers2

137

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

dtb
  • 198,715
  • 31
  • 379
  • 417
  • 1
    Say i have /folder1/folder2/folder3/folder4/file.txt as the filename and folder1 doesn't exist. Will the above create all 4 folders. – Ash Burlaczenko Sep 12 '10 at 14:29
  • @Ash Burlaczenko: I just tested it and, yes, it does. – dtb Sep 12 '10 at 14:30
  • What would happen if the folder already existed and you ran that line – Ash Burlaczenko Sep 12 '10 at 14:37
  • 3
    @Ash Burlaczenko: Directory.CreateDirectory does not throw an exception if the directory already exists. It does nothing in this case. – dtb Sep 12 '10 at 14:43
  • Thats exactly what i need then. Thank you. +1 – Ash Burlaczenko Sep 12 '10 at 14:55
  • 6
    One edge case where this will throw an exception is if the input filename does not contain a path (e.g. "text1.txt"). In this case, Path.GetDirectoryName will return an empty string, and Directory.CreateDirectory with throw an ArgumentException. – Joe Sep 12 '10 at 15:56
17

Something like:

void EnsureFolder(string path)
{
    string directoryName = Path.GetDirectoryName(path);
    // If path is a file name only, directory name will be an empty string
    if (directoryName.Length > 0)
    {
        // Create all directories on the path that don't already exist
        Directory.CreateDirectory(directoryName);
    }
}
Joe
  • 114,633
  • 27
  • 187
  • 321
  • 1
    Why is this so less upvoted, its a good way to check and create folder. – Chaitanya Gadkari Jun 01 '15 at 11:14
  • 2
    @ChaitanyaGadkari likely because Directory.CreateDirectory does not throw an exception if the directory already exists; so dtb's answer is succinct for most people facing a similar problem. – nullable May 25 '17 at 09:51