[英]How do I create directory if it doesn't exist to create a file?
I have a piece of code here that breaks if the directory doesn't exist:如果目录不存在,我在这里有一段代码会中断:
System.IO.File.WriteAllText(filePath, content);
In one line (or a few lines), is it possible to check if the directory leading to the new file doesn't exist and if not, to create it before creating the new file?在一行(或几行)中,是否可以检查通向新文件的目录是否不存在,如果不存在,则在创建新文件之前创建它?
I'm using .NET 3.5.我正在使用 .NET 3.5。
(new FileInfo(filePath)).Directory.Create()
before writing to the file. (new FileInfo(filePath)).Directory.Create()
在写入文件之前。
System.IO.FileInfo file = new System.IO.FileInfo(filePath);
file.Directory.Create(); // If the directory already exists, this method does nothing.
System.IO.File.WriteAllText(file.FullName, content);
您可以使用以下代码
DirectoryInfo di = Directory.CreateDirectory(path);
正如@hitec 所说,你必须确保你拥有正确的权限,如果你这样做了,你可以使用这一行来确保目录的存在:
Directory.CreateDirectory(Path.GetDirectoryName(filePath))
An elegant way to move your file to an nonexistent directory is to create the following extension to native FileInfo class:将文件移动到不存在的目录的一种优雅方法是为本机 FileInfo 类创建以下扩展:
public static class FileInfoExtension
{
//second parameter is need to avoid collision with native MoveTo
public static void MoveTo(this FileInfo file, string destination, bool autoCreateDirectory) {
if (autoCreateDirectory)
{
var destinationDirectory = new DirectoryInfo(Path.GetDirectoryName(destination));
if (!destinationDirectory.Exists)
destinationDirectory.Create();
}
file.MoveTo(destination);
}
}
Then use brand new MoveTo extension:然后使用全新的 MoveTo 扩展:
using <namespace of FileInfoExtension>;
...
new FileInfo("some path")
.MoveTo("target path",true);
Check Methods extension documentation .检查方法扩展文档。
You can use File.Exists to check if the file exists and create it usingFile.Create if required.您可以使用File.Exists检查文件是否存在,并在需要时使用File.Create创建它。 Make sure you check if you have access to create files at that location.确保检查您是否有权在该位置创建文件。
Once you are certain that the file exists, you can write to it safely.一旦确定文件存在,就可以安全地写入文件。 Though as a precaution, you should put your code into a try...catch block and catch for the exceptions that function is likely to raise if things don't go exactly as planned.尽管作为预防措施,您应该将代码放入 try...catch 块中,并捕获如果事情没有完全按计划进行,该函数可能会引发的异常。
Additional information for basic file I/O concepts . 有关基本文件 I/O 概念的附加信息。
var filePath = context.Server.MapPath(Convert.ToString(ConfigurationManager.AppSettings["ErrorLogFile"]));
var file = new FileInfo(filePath);
file.Directory.Create();
If the directory already exists, this method does nothing.如果目录已经存在,则此方法不执行任何操作。
var sw = new StreamWriter(filePath, true);
sw.WriteLine(Enter your message here);
sw.Close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.