如果目录不存在,我在这里有一段代码会中断:
System.IO.File.WriteAllText(filePath, content);
Run Code Online (Sandbox Code Playgroud)
在一行(或几行)中,是否可以检查导致新文件的目录是否不存在,如果不存在,是否可以在创建新文件之前创建它?
我正在使用.NET 3.5.
Don*_*Don 373
(new FileInfo(filePath)).Directory.Create()
Before writing to the file.
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);
Run Code Online (Sandbox Code Playgroud)
Ram*_*Ram 103
You can use following code
DirectoryInfo di = Directory.CreateDirectory(path);
Run Code Online (Sandbox Code Playgroud)
wil*_*lvv 31
As @hitec said, you have to be sure that you have the right permissions, if you do, you can use this line to ensure the existence of the directory:
Directory.CreateDirectory(Path.GetDirectoryName(filePath))
归档时间: |
|
查看次数: |
147280 次 |
最近记录: |