正确等待文件创建的方法

编程入门 行业动态 更新时间:2024-10-27 20:25:17
本文介绍了正确等待文件创建的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下代码:

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

P.S. I am using framework 3.5

即使我等待它崩溃:/

Even if I wait it crashes :/

推荐答案

原因是因为 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.

更多推荐

正确等待文件创建的方法

本文发布于:2023-11-06 17:37:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1564349.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正确   文件   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!