我有一个目录路径,如何创建所有的目录?例如,如果C:\Match\Upload不存在,则同时创建Match和子目录Upload。
使用C# 3.0
谢谢
Directory.CreateDirectory(@"C:\Match\Upload")会为您解决这一切。 您无需创建所有子目录! 创建目录方法会为您创建所有的目录和子目录。
if (!System.IO.Directory.Exists(@"C:\Match\Upload"))
{
System.IO.Directory.CreateDirectory(@"C:\Match\Upload");
}
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();
针对谷歌用户:在纯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
}