创建目录+子目录
答
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
}
答
这是一个带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();
参考https://msdn.microsoft.com/en-us/library/system.io.directory.createdirectory.aspx – 2015-12-09 15:01:25