【发布时间】:2014-05-07 06:05:57
【问题描述】:
在wince 5.0 / .net framework compact 2.0上运行的代码
总是得到一个异常说:
该进程无法访问该文件,因为它正被另一个进程使用。
真的很困惑,因为我已经在 using 语句中包含了流,所以一旦离开 using 块,文件流应该自动关闭。
//read text
using (StreamReader sr = File.OpenText(fname))
{
string line;
while ((line = sr.ReadLine()) != null)
{
// append into stringbuilder
sb.Append(line);
sb.Append("\n");
}
}
//write text, below code raise the exception.
//if i comment it and re-run the code,exception disappear
using (StreamWriter sw = File.CreateText(fname))
{
sw.Write(sb.ToString());
}
补充:我只是想更新文件,读写。有更好的方法吗?
【问题讨论】:
-
如果您在 StreamWriter 之前添加断点并尝试手动编辑文件怎么办?只是为了检查它是否可能是一些权限错误。
-
也许问题不在您的代码中。是否有另一个进程(在您的应用程序旁边)使用此文件?
-
如果我错了,请纠正我,但是 using 语句只保证 reader 会被处理掉,而不是在下一个 using 语句之前处理掉它。除非您调用 Close(),否则您无法控制文件何时关闭。
-
确保该文件尚未打开。 ?
-
fname 在哪里?这似乎是一个权限问题。
标签: c#