等待文件创建的正确方法

Proper way of waiting until a file is created

我有以下代码:

// 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");

此代码在最后一行崩溃 (An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll)。如果我在创建文件后放置一个 Thread.Sleep(400) 代码效果很好。 等待文件创建的正确方法是什么?

P.S。 我正在使用 .net 框架 3.5

即使我等待它也会崩溃:/

如果您打算使用 File.AppendAllText

,则无需创建文件

关于错误的根本原因,以及一般写入文件的首选方式:

文件已创建,并返回了一个您没有 use/close 的流。最好的方法应该是使用这个流来写入文件。

using (FileStream fs = File.Create(file))
{
     fs.Write("What ever you need to write..");
}

这是因为 File.Create 声明为:

public static FileStream Create(
    string path
)

它returns一个FileStream。该方法应该用于创建和打开文件以进行写入。由于您从不处理返回的 FileStream 对象,因此您基本上是在押注垃圾收集器在需要重写文件之前收集该对象。

因此,要使用天真的解决方案解决问题,您应该处理该对象:

System.IO.File.Create(file).Dispose();

现在,问题是 File.AppendAllText 实际上会创建文件(如果它不存在),因此您甚至不需要该代码,这是删除了不必要代码的完整代码:

// 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 同样不会崩溃,因此您可以安全地调用它。