73

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
  • 160,644
  • 26
  • 247
  • 397
Ash Burlaczenko
  • 24,778
  • 15
  • 68
  • 99

2 Answers2

151

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
  • 213,145
  • 36
  • 401
  • 431
  • 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. – Ash Burlaczenko Sep 12 '10 at 14:29
  • 1
    @Ash Burlaczenko: I just tested it and, yes, it does. – dtb Sep 12 '10 at 14:30
  • 3
    What would happen if the folder already existed and you ran that line – Ash Burlaczenko Sep 12 '10 at 14:37
  • 5
    @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
  • 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 Sep 12 '10 at 15:56
  • I tested this in Linux with .NET 6 and it created a folder with the name of the file. Testing in Windows it doesn't create a folder named text1.txt. – Ernesto Gutierrez Oct 12 '22 at 05:00
21

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
  • 122,218
  • 32
  • 205
  • 338
  • 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