FileStream and creating folders

2019-01-23 00:32发布

问题:

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.

回答1:

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



回答2:

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


标签: c# filestream