Create Directory + Sub Directories
I've got a directory l开发者_如何学Cocation, how can I create all the directories? e.g. C:\Match\Upload will create both Match and the sub-directory Upload if it doesn't exist.
Using C# 3.0
Thanks
Directory.CreateDirectory(@"C:\Match\Upload") will sort this all out for you. You don't need to create all the subdirectories! The create directory method creates all directories and sub directories for you.
if (!System.IO.Directory.Exists(@"C:\Match\Upload"))
{
System.IO.Directory.CreateDirectory(@"C:\Match\Upload");
}
Here is an example with a DirectoryInfo
object that will create the directory and all subdirectories:
var path = @"C:\Foo\Bar";
new System.IO.DirectoryInfo(path).Create();
Calling Create()
will not error if the path already exists.
If it is a file path you can do:
var path = @"C:\Foo\Bar\jazzhands.txt";
new System.IO.FileInfo(path).Directory.Create();
for googlers: in pure win32/C++, use 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
}
精彩评论