Proper way of waiting until a file is created

守給你的承諾、 提交于 2019-12-02 01:10:06

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.

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..");
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!