如果创建目录不存在以创建文件,该如何创建目录?
我有一段代码在这里,如果目录不存在,打破:如果创建目录不存在以创建文件,该如何创建目录?
System.IO.File.WriteAllText(filePath, content);
在一个行(或几行),则可以检查目录通往新文件没有按是否存在,如果没有,在创建新文件之前创建它?
我正在使用.NET 3.5。
(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);
优雅的解决方案,因为它处理需要创建嵌套文件夹的情况。 – 2017-05-08 20:57:34
如果需要,您可以使用File.Exists来检查文件是否存在并使用File.Create来创建它。确保您检查是否有权在该位置创建文件。
一旦确定文件存在,您可以安全地写入文件。尽管作为一项预防措施,您应该将代码放入try ... catch块,并捕获函数可能会引发的异常,如果事情没有按计划完成。
我最初误读了你想写入一个可能不存在的文件的问题。尽管文件和目录IO的概念基本相同。 – hitec 2010-06-02 06:24:29
您可以使用下面的代码
DirectoryInfo di = Directory.CreateDirectory(path);
'Directory.CreateDirectory'完全符合你的要求:它创建目录,如果它还不存在。 **没有必要先做一个明确的检查**。 – 2012-10-08 15:45:27
如果'path'是文件而不是目录,则抛出IOException。 https://msdn.microsoft.com/zh-cn/library/54a0at6s(v=vs.110).aspx – scaryman 2015-04-15 22:31:20
正如@hitec说,你要确保你有正确的权限,如果你这样做,你可以使用这条线确保该目录的存在:
Directory.CreateDirectory(Path.GetDirectoryName(filePath))
var filePath = context.Server.MapPath(Convert.ToString(ConfigurationManager.AppSettings["ErrorLogFile"]));
var file = new FileInfo(filePath);
file.Directory.Create();
如果该目录已经存在,这个方法不起作用。
var sw = new StreamWriter(filePath, true);
sw.WriteLine(Enter your message here);
sw.Close();
的可能的复制[如果文件夹不存在,创建它(http://stackoverflow.com/questions/9065598/if-a-folder -does-not-exist-create-it) – 2016-11-28 03:05:49