C# 创建目录 + 子目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1680836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:58:07  来源:igfitidea点击:

Create Directory + Sub Directories

c#

提问by Lennie

I've got a directory location, how can I create all the directories? e.g. C:\Match\Upload will create both Match and the sub-directory Upload if it doesn't exist.

我有一个目录位置,如何创建所有目录?例如 C:\Match\Upload 将创建 Match 和子目录 Upload 如果它不存在。

Using C# 3.0

使用 C# 3.0

Thanks

谢谢

采纳答案by RichardOD

Directory.CreateDirectory(@"C:\Match\Upload") will sort this all out for you. You don't need to create all the subdirectories! The create directory method creates all directories and sub directories for you.

Directory.CreateDirectory(@"C:\Match\Upload") 将为您解决所有问题。您不需要创建所有子目录!create directory 方法为您创建所有目录和子目录。

回答by RichardOD

if (!System.IO.Directory.Exists(@"C:\Match\Upload"))
{
  System.IO.Directory.CreateDirectory(@"C:\Match\Upload");
}

回答by Dustin Getz

for googlers: in pure win32/C++, use SHCreateDirectoryEx

对于 googlers:在纯 win32/C++ 中,使用SHCreateDirectoryEx

inline void EnsureDirExists(const std::wstring& fullDirPath)
{
    HWND hwnd = NULL;
    const SECURITY_ATTRIBUTES *psa = NULL;
    int retval = SHCreateDirectoryEx(hwnd, fullDirPath.c_str(), psa);
    if (retval == ERROR_SUCCESS || retval == ERROR_FILE_EXISTS || retval == ERROR_ALREADY_EXISTS)
        return; //success

    throw boost::str(boost::wformat(L"Error accessing directory path: %1%; win32 error code: %2%") 
        % fullDirPath
        % boost::lexical_cast<std::wstring>(retval));

    //TODO *djg* must do error handling here, this can fail for permissions and that sort of thing
}

回答by Chad Kuehn

Here is an example with a DirectoryInfoobject that will create the directory and all subdirectories:

这是一个DirectoryInfo将创建目录和所有子目录的对象示例:

var path = @"C:\Foo\Bar";
new System.IO.DirectoryInfo(path).Create();

Calling Create()will not error if the path already exists.

Create()如果路径已经存在,调用不会出错。

If it is a file path you can do:

如果它是文件路径,您可以执行以下操作:

var path = @"C:\Foo\Bar\jazzhands.txt";
new System.IO.FileInfo(path).Directory.Create();