如何创建一个文件和任何文件夹,如果文件夹不存在? [英] How do I create a file AND any folders, if the folders don't exist?
问题描述
想象我希望创建(或覆盖)以下文件: - C:\ TEMP \酒吧\富\ Test.txt的
使用 File.Create(..)的方法,这样可以做到这一点。
但是,如果我没有任何一个下列文件夹(从例如道路,上面)
- 温度
- 在酒吧
- 富
然后我得到的<一个href="http://msdn.microsoft.com/en-us/library/system.io.directorynotfoundexception.aspx">DirectoryNotFoundException抛出。
所以.. 给出一个路径,我们怎么能递归创造一切必要创建该文件的文件夹。对于这条道路?如果温度或酒吧的文件夹存在,但富不... ,那么这也创造了。
为了简单起见,让我们假设有没有安全问题 - 所有的权限都很好,等
//判断是否该目录存在。
如果(Directory.Exists(路径))
{
Console.WriteLine(那路径已经存在。);
返回;
}
//尝试创建目录。
DirectoryInfo的迪= Directory.CreateDirectory(路径);
Console.WriteLine(目录成功为{0}创建。
Directory.GetCreationTime(路径));
请参阅这个MSDN页面。
希望帮助了!
imagine i wish to create (or overwrite) the following file :- C:\Temp\Bar\Foo\Test.txt
Using the File.Create(..) method, this can do it.
BUT, if i don't have either one of the following folders (from that example path, above)
- Temp
- Bar
- Foo
then i get an DirectoryNotFoundException thrown.
So .. given a path, how can we recursively create all the folders necessary to create the file .. for that path? If Temp or Bar folders exists, but Foo doesn't... then that is created also.
For simplicity, lets assume there's no Security concerns -- all permissions are fine, etc.
// Determine whether the directory exists.
if (Directory.Exists(path))
{
Console.WriteLine("That path exists already.");
return;
}
// Try to create the directory.
DirectoryInfo di = Directory.CreateDirectory(path);
Console.WriteLine("The directory was created successfully at {0}.",
Directory.GetCreationTime(path));
See this MSDN page.
Hope that helps out!
这篇关于如何创建一个文件和任何文件夹,如果文件夹不存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!