【问题标题】:The process can't access the file, because it is being used by another process [duplicate]该进程无法访问该文件,因为它正在被另一个进程使用[重复]
【发布时间】: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/…

标签: c# .net file-io


【解决方案1】:

您不能使用 FileMode.OpenOrCreate 选项创建 FileStream 吗?而不是文件?

【讨论】:

    【解决方案2】:

    使用 (StreamWriter sw = new StreamWriter(CConstant.m_TEMPFILEPATH, true))

    把你的代码换成upper的代码,测试一下,也是一样的结果吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-10
      相关资源
      最近更新 更多