创建目录+子目录

创建目录+子目录

问题描述:

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

使用C#3.0

感谢

Directory.CreateDirectory(@ “C:\匹配\上传”)将整理出这一切为您服务。你不需要创建所有的子目录!创建目录方法为您创建所有目录和子目录。

+0

参考https://msdn.microsoft.com/en-us/library/system.io.directory.createdirectory.aspx – 2015-12-09 15:01:25

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

目录可能不存在于if中,但在使用该方法创建尝试期间仍然存在。不要打扰存在和使用捕获。 – 2009-11-05 14:32:43

+7

即使目录存在,实际调用CreateDirectory也不会失败,因此使用它是多余的。 – RichardOD 2011-11-30 13:31:26

为Google员工:在纯粹的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 
} 
+0

只有Windows XP和2003,说文档 – MikMik 2011-11-25 15:15:04

+0

这位家伙问到C#,但这正是我要找的:-) – 2013-01-22 23:11:51

+1

从什么时候开始提升纯win32 – Kobor42 2015-04-12 23:32:14

这是一个带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();