【问题标题】:Proper way of waiting until a file is created等待文件创建的正确方法
【发布时间】:2015-10-03 19:38:00
【问题描述】:

我有以下代码:

// 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),则代码效果很好。 等待文件创建的正确方法是什么?

附: 我正在使用 .net 框架 3.5

即使我等待它崩溃:/

【问题讨论】:

  • 我认为您不需要创建它,因为 AppendAllText 如果文件不存在则应该创建它。这也可能是当您尝试附加文本时打开文件时出现异常的原因。对于其他文件,您也可以使用“using”语句。
  • System.IO.File.AppendAllText 如果文件不存在,则创建一个文件,因此您不必先创建它。我只能假设对 File.Create 的调用创建了一个已清理的 FileStream 对象,但速度不够快,不会在您调用 AppendAllText 时阻止该文件。
  • 抱歉这个愚蠢的问题。我想我累了大声笑

标签: c# io file-writing


【解决方案1】:

之所以这样是因为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 同样不会在文件夹已存在的情况下崩溃,因此您可以安全地调用它。

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2017-09-09
      • 2015-11-30
      • 1970-01-01
      • 1970-01-01
      • 2010-09-24
      • 2014-11-15
      • 1970-01-01
      • 1970-01-01
      • 2020-08-01
      相关资源
      最近更新 更多