2009-11-05 202 views
28

我有一個目錄位置,我如何創建所有的目錄?例如如果不存在,C:\ Match \ Upload將同時創建Match和子目錄Upload。創建目錄+子目錄

使用C#3.0

感謝

回答

56

Directory.CreateDirectory(@ 「C:\匹配\上傳」)將整理出這一切爲您服務。你不需要創建所有的子目錄!創建目錄方法爲您創建所有目錄和子目錄。

+0

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

8
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

1

爲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

0

這是一個帶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();