【发布时间】: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