FileStream and creating folders

C#Filestream

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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);
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAsh BurlaczenkoView Question on Stackoverflow
Solution 1 - C#dtbView Answer on Stackoverflow
Solution 2 - C#JoeView Answer on Stackoverflow