[英]How to create multiple directories from a single full path in C#?
If you have a full path like: "C:\\dir0\\dir1\\dir2\\dir3\\dir4\\"
how would you best implement it so that all directories are present? 如果你有一个完整的路径,如:
"C:\\dir0\\dir1\\dir2\\dir3\\dir4\\"
你将如何最好地实现它,以便所有目录都存在?
Is there a method for this in the BCL? 在BCL中有这种方法吗? If not, what's the most elegant way to do this?
如果没有,那么最优雅的方式是什么?
I would call Directory.CreateDirectory(@"C:\\dir0\\dir1\\dir2\\dir3\\dir4\\")
. 我会调用
Directory.CreateDirectory(@"C:\\dir0\\dir1\\dir2\\dir3\\dir4\\")
。
Contrary to popular belief, Directory.CreateDirectory
will automatically create whichever parent directories do not exist. 与流行的看法相反,
Directory.CreateDirectory
将自动创建不存在的父目录。
In MSDN's words, Creates all directories and subdirectories as specified by path.
用MSDN的话来说,
Creates all directories and subdirectories as specified by path.
If the entire path already exists, it will do nothing. 如果整个路径已经存在,它将什么都不做。 (It won't throw an exception)
(它不会抛出异常)
Create directories from complete filepath 从完整文件路径创建目录
private String EvaluatePath(String path){
try
{
String folder = Path.GetDirectoryName(path);
if (!Directory.Exists(folder))
{
// Try to create the directory.
DirectoryInfo di = Directory.CreateDirectory(folder);
}
}
catch (IOException ioex)
{
Console.WriteLine(ioex.Message);
return "";
}
return path;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.