开发者

FileStream and creating folders

开发者 https://www.devze.com 2023-01-15 15:38 出处:网络
Just a quick question. I\'m using something like this FileStream fs = new F开发者_运维知识库ileStream(fileName, FileMode.Create);

Just a quick question. I'm using something like this

FileStream fs = new F开发者_运维知识库ileStream(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.


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


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

精彩评论

暂无评论...
验证码 换一张
取 消