(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);
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);
}
}
然后使用全新的MoveTo扩展:
using <namespace of FileInfoExtension>;
...
new FileInfo("some path")
.MoveTo("target path",true);