FileStream 和创建文件夹

发布于 2024-09-19 00:00:18 字数 218 浏览 2 评论 0原文

只是一个简单的问题。我正在使用类似的东西,

FileStream fs = new FileStream(fileName, FileMode.Create);

我想知道是否有一个参数可以传递给它以强制它创建文件夹(如果它不存在)。目前,如果找不到文件夹,则会引发异常。

如果有更好的方法,那么使用 FileStream 我愿意接受想法。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

予囚 2024-09-26 00:00:18

使用 Directory.CreateDirectory

Directory.CreateDirectory 方法(字符串)

创建路径指定的所有目录和子目录。

示例:

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 返回目录文件名的一部分。)

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

唠甜嗑 2024-09-26 00:00:18

像这样的东西:

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

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);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文