正确等待文件创建的方法 [英] Proper way of waiting until a file is created

查看:137
本文介绍了正确等待文件创建的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

此代码在最后一行崩溃(类型为'System'的未处理异常mscorlib.dll 中发生了.IO.IOException。如果我在创建文件后放置 Thread.Sleep(400),则代码效果很好。 在创建文件之前等待的正确方法是什么?

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。
我正在使用.net framework 3.5

P.S. I am using .net framework 3.5

即使我等待它崩溃:/

Even if I wait it crashes :/

< a href =https://i.stack.imgur.com/ZKJ0c.png =nofollow noreferrer>

推荐答案

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

public static FileStream Create(
    string path
)

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

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();

现在,问题在于 File.AppendAllText 实际上会创建文件,如果它不存在所以你甚至不需要那些代码,这里是你的完整代码,删除了不必要的代码:

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 同样不会崩溃该文件夹已存在,因此您可以安全地调用它。

Directory.CreateDirectory will likewise not crash if the folder already exists so you can safely just call it.

这篇关于正确等待文件创建的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆