【发布时间】:2011-09-02 22:33:43
【问题描述】:
可能重复:
Cant Access File because it is being used by another process
using (StreamWriter _SelectedFile = File.CreateText(CConstant.m_TEMPFILEPATH))
{
_SelectedFile.WriteLine(CConstant.m_SaveFileDefaultDirectory);
_SelectedFile.WriteLine(CConstant.Tempfile_ECUSelected);
_SelectedFile.WriteLine(CConstant.Tempfile_inifile);
_SelectedFile.WriteLine(CConstant.Tempfile_mapfile);
_SelectedFile.Flush();
_SelectedFile.Close();
_SelectedFile.Dispose();
}
运行代码时,当我第一次运行代码时(没有 temp.txt 文件),它会抛出异常“进程无法访问该文件,因为它正在被另一个进程使用。 "请提出一个解决方案,以及以这种方式编写代码有什么问题?
【问题讨论】:
-
您不需要 .Flush、.Close 和 .Dispose。当您离开 using 范围时,所有这些都将自动完成。现在您说第一次不存在 temp.txt 文件,但您得到一个异常,指出该文件已被另一个进程使用。那是什么?
-
代码没有问题(除了 Flush/Close/Dispose 序列没用)。错误信息非常清楚:另一个进程已经在使用该文件,所以你不能写入它
-
@Darin Dimitrov:是的..第一次,当我运行代码时..没有这样的文件存在..它仍然会弹出一个异常。
-
@Kritika,你意识到这没有意义吗?
-
这个问题已经在 SO stackoverflow.com/questions/321077/…