【问题标题】:The process cannot access the file 'C:\file.xml' because it is being used by another process该进程无法访问文件“C:\file.xml”,因为它正被另一个进程使用
【发布时间】:2012-03-30 20:06:43
【问题描述】:
 DirectoryInfo dir=new DirectoryInfo(path);
 if (!dir.Exists)
  {
      Directory.CreateDirectory(path);
      File.Create(path + "\\file.xml");

      StreamWriter sw =new StreamWriter(path + "\\file.xml");
      sw.Flush();
      sw.Write("<?xml version='1.0' encoding='utf-8' ?><project></project>");
  }

错误:

进程无法访问文件“C:\file.xml”,因为它正在 被另一个进程使用。

为什么?如何关闭文件?

【问题讨论】:

    标签: c# c#-4.0 file-io


    【解决方案1】:

    From MSDN

    此方法 (File.Create) 创建的 FileStream 对象的默认 FileShare 值为 None;在关闭原始文件句柄之前,没有其他进程或代码可以访问创建的文件。

    所以解决方法是

      using(FileStream fs = File.Create(path + "\\file.xml"))
      {
           Byte[] info = new UTF8Encoding(true).GetBytes("<?xml version='1.0' encoding='utf-8' ?><project></project>");
           fs.Write(info, 0, info.Length);
      }
    

    编辑:更改删除 StreamWriter 的创建并使用 FileStream
    但是我不喜欢 MSDN 建议的这种方式。
    StreamWriter 有一个构造函数,可以获取 FileStream,但我想如果我们使用

       using(StreamWriter sw = new StreamWriter(File.Create(path + "\\file.xml")))
       { 
          sw.Write("<?xml version='1.0' encoding='utf-8' ?><project></project>");
       }
    

    我们找回了锁定问题。但是,我已经测试过了,它可以工作。
    可能 StreamWriter 构造函数对 File.Create 返回的 FileStream 做了一些技巧。

    【讨论】:

    • 错误:无法将类型'System.IO.FileStream'隐式转换为'System.IO.StreamWriter'
    【解决方案2】:

    使用File.CreateStreamWriter,不能同时使用

    【讨论】:

    • 请写一个示例,创建然后添加到
    • @user1263390 StreamWriter sw = new StreamWriter(path + "\\file.xml", false);
    【解决方案3】:

    改变

    File.Create(path + "\\file.xml");
    

    File.Create(path + "\\file.xml").Close();
    

    【讨论】:

      【解决方案4】:

      在你打电话给Write();之后再做sw.Close();

      使用 XmlDocument 可能会更好。然后你可以追加节点等节点。

      XmlDocument 具有内置的保存功能,因此您无需像流写入器那样管理任何功能。

      【讨论】:

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