创建目录及其子目录

47

我有一个目录路径,如何创建所有的目录?例如,如果C:\Match\Upload不存在,则同时创建Match和子目录Upload。

使用C# 3.0

谢谢

4个回答

84

Directory.CreateDirectory(@"C:\Match\Upload")会为您解决这一切。 您无需创建所有子目录! 创建目录方法会为您创建所有的目录和子目录。


请参考:https://msdn.microsoft.com/zh-cn/library/system.io.directory.createdirectory.aspx - Stéphane Gourichon

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

1
该目录在 if 语句中可能不存在,但在使用该方法进行创建尝试时仍然存在。不要担心 exists,而是使用 catch。 - user159335
14
实际上,即使目录已经存在,调用CreateDirectory也不会失败,因此使用它是多余的。 - RichardOD

4
这里有一个示例,使用 DirectoryInfo 对象可以创建目录及其所有子目录:
var path = @"C:\Foo\Bar";
new System.IO.DirectoryInfo(path).Create();

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

如果它是一个文件路径,你可以这样做:

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

0

针对谷歌用户:在纯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
}

文档中写明仅支持Windows XP和2003。 - MikMik
2
Boost 纯 Win32 是从什么时候开始的? - Kobor42

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接