正确等待文件创建的方法

我有以下代码:

// 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) ,则代码运行良好。 在文件创建之前等待的正确方法是什么?

PS我正在使用.net framework 3.5

即使我等它崩溃:/

在此处输入图像描述

原因是因为File.Create声明为:

 public static FileStream Create( string path ) 

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

如果您打算使用File.AppendAllText则无需创建该文件

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

该文件已创建,并返回了您未使用/关闭的流。 最好的方法应该是使用此流写入文件。

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