问题
I have the following code:
// get location where application data director is located
var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
// create dir if it doesnt exist
var folder = System.IO.Path.Combine(appData, "SomeDir");
if (System.IO.Directory.Exists(folder) == false)
System.IO.Directory.CreateDirectory(folder);
// create file if it doesnt exist
var file = System.IO.Path.Combine(folder, "test.txt");
if(System.IO.File.Exists(file)== false)
System.IO.File.Create(file);
// write something to the file
System.IO.File.AppendAllText(file,"Foo");
This code crashes on the last line (An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
). If I put a Thread.Sleep(400)
after creating the file the code works great. What is the proper way of waiting until the file is created?
P.S. I am using .net framework 3.5
Even if I wait it crashes :/
回答1:
The reason for that is because File.Create is declared as:
public static FileStream Create(
string path
)
It returns a FileStream
. The method is supposed to be used to create and open a file for writing. Since you never dispose of the returned FileStream
object you're basically placing your bets on the garbage collector to collect that object before you need to rewrite the file.
So, to fix the problem with the naive solution you should dispose of that object:
System.IO.File.Create(file).Dispose();
Now, the gotcha here is that File.AppendAllText
will in fact create the file if it does not exist so you don't even need that code, here is your full code with the unnecessary code removed:
// get location where application data director is located
var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
// create dir if it doesnt exist
var folder = System.IO.Path.Combine(appData, "SomeDir");
System.IO.Directory.CreateDirectory(folder);
// write something to the file
var file = System.IO.Path.Combine(folder, "test.txt");
System.IO.File.AppendAllText(file,"Foo");
Directory.CreateDirectory
will likewise not crash if the folder already exists so you can safely just call it.
回答2:
There is no need to create the file if you intend to use File.AppendAllText
About the root cause for the error, and a preferred way to write to files in general:
The file was created, and returned a stream that you didn't use/close. best method should be to use this stream to write to the file.
using (FileStream fs = File.Create(file))
{
fs.Write("What ever you need to write..");
}
来源:https://stackoverflow.com/questions/32926707/proper-way-of-waiting-until-a-file-is-created