tags:

views:

58

answers:

3

Hi everyone

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.

Thank you in advance.

A: 

You can use the File.Exists() method to see if the file exists or not, then use the appropriate enumeration, depending on the result of the Exists method. There is a small example available here.

npinti
+5  A: 

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
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
@Ash Burlaczenko: I just tested it and, yes, it does.
dtb
What would happen if the folder already existed and you ran that line
Ash Burlaczenko
@Ash Burlaczenko: Directory.CreateDirectory does not throw an exception if the directory already exists. It does nothing in this case.
dtb
Thats exactly what i need then. Thank you. +1
Ash Burlaczenko
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
+1  A: 

Something like:

void EnsureFolder(string path)
{
    string directoryName = Path.GetDirectoryName(path);
    if ((directoryName.Length > 0) && (!Directory.Exists(directoryName))
    {
        Directory.CreateDirectory(directoryName);
    }
}
Joe