76

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.

2 Answers 2

154

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

6
  • 2
    Say i have /folder1/folder2/folder3/folder4/file.txt as the filename and folder1 doesn't exist. Will the above create all 4 folders. Commented Sep 12, 2010 at 14:29
  • 1
    @Ash Burlaczenko: I just tested it and, yes, it does.
    – dtb
    Commented Sep 12, 2010 at 14:30
  • 5
    What would happen if the folder already existed and you ran that line Commented Sep 12, 2010 at 14:37
  • 7
    @Ash Burlaczenko: Directory.CreateDirectory does not throw an exception if the directory already exists. It does nothing in this case.
    – dtb
    Commented Sep 12, 2010 at 14:43
  • 8
    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
    Commented Sep 12, 2010 at 15:56
20

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);
    }
}
2
  • 1
    Why is this so less upvoted, its a good way to check and create folder. Commented Jun 1, 2015 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
    Commented May 25, 2017 at 9:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.