C# 创建路径不存在的文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1321149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a File that the Path does not exists?
提问by Athiwat Chunlakhan
I just can't get around this. I am able to create a file with File.Create
... File.CrateText
and so on, only if the path exists. If it does not the file will not we written and returns an error. How do I create the path?
我就是无法解决这个问题。仅当路径存在时,我才能使用File.Create
...File.CrateText
等创建文件。如果不是,文件将不会被我们写入并返回错误。如何创建路径?
采纳答案by Sklivvz
回答by Lloyd Powell
You will need to create the Directory first. It will create all of the subdirectories that don't exist within the path you send it. It's quite a powerful piece of functionality.
您需要先创建目录。它将创建您发送的路径中不存在的所有子目录。这是一个非常强大的功能。
Directory.CreateDirectory(filePath);
If you don't know whether the directory exists or not you can use Directory.Exists. But not for this case as it would be pointless. MSDN states that CreateDirectory does nothing if the directory currently exists. But if you wanted to check existance of the directory for another reason you can use:
如果您不知道目录是否存在,您可以使用 Directory.Exists。但不适用于这种情况,因为它毫无意义。MSDN 声明如果目录当前存在,则 CreateDirectory 不执行任何操作。但是,如果您出于其他原因想检查目录的存在,您可以使用:
if(Directory.Exists(folder) == false)
{
//do stuff
}
回答by x2.
Directory.CreateDirectory("path");
回答by Ashraf Alam
Given that you've the full path (Folder + File name), the following code will ensure your required directory path exists (if it does not exist already)
鉴于您拥有完整路径(文件夹 + 文件名),以下代码将确保您需要的目录路径存在(如果尚不存在)
FileInfo fileInfo = new FileInfo(fileFullPath);
if (!fileInfo.Exists)
Directory.CreateDirectory(fileInfo.Directory.FullName);
//create the file ...
回答by harishr
below should also work
下面也应该工作
FileInfo fileInfo = new FileInfo(fileFullPath);
if (!fileInfo.Directory.Exists) fileInfo.Directory.Create()
work on directory of fileinfo, rather than static directory class
处理文件信息目录,而不是静态目录类