【问题标题】:System.IO.IOException error, can't get access to the fileSystem.IO.IOException 错误,无法访问文件
【发布时间】:2013-12-04 08:05:06
【问题描述】:

我不明白问题出在哪里,尽管这段代码很简单。

我有这样的功能:

public void WriteToDoc(string path)    
{
     XDocument doc = new XDocument(new XElement("General parameters",
                                   new XElement("num_path", num_path.Text),
                                   new XElement("Gen_Peroid", Gen_Peroid.Text),
                                   new XElement("Alg_Perioad", Alg_Perioad.Text))
                                  );
     doc.Save(path); // here he gives that exception
}

num_path.TextGen_Peroid.TextAlg_Perioad.Textstring

我是这样使用这个功能的:

File.Create(@"C:\ProgramData\RadiolocationQ\Q.xml");
WriteToDoc(@"C:\ProgramData\RadiolocationQ\Q.xml");

它创建文件,但该文件中没有写入任何内容。所以确切的错误System.IO.IOException 错误,该进程无法访问该文件,因为它正在被另一个进程使用。怎么可能出现这样的错误?

【问题讨论】:

    标签: c# linq-to-xml file-access


    【解决方案1】:

    试试

    System.IO.File.Create(@"C:\ProgramData\RadiolocationQ\Q.xml").Close();
    

    编辑:莱因哈兹的答案更好。我只是关闭 File.Create() 流,它锁定了文件,但没有必要。

    【讨论】:

      【解决方案2】:

      正如其他答案所述,您没有关闭输出文件。使用 LinqToXML 保存 XML 文件的正确方法是:

      System.Xml.XmlWriterSettings xws = new System.Xml.XmlWriterSettings();
      xws.Indent = true;
      xws.IndentChars = "\t";
      
      FileStream fsConfig = new FileStream(path, FileMode.Create);
      using (System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(fsConfig, xws))
      {
             doc.Save(xw);
      }
      fsConfig.Close();
      

      这会释放文件和流。如果不需要,您可以省略XmlWriterSettings

      【讨论】:

        【解决方案3】:

        你是打开它的进程!

        不要先调用File.Create - 它会使文件流处于打开状态,并且您无法覆盖文件。

        XDocument.Save 将创建文件 - 您不必这样做:

        将此 XDocument 序列化为文件,覆盖现有文件(如果存在)。

        【讨论】:

          【解决方案4】:

          XDocument.Save 将创建一个不存在的文件。不需要File.Create()

          File.Create() 没有关闭,它正在锁定你的文件。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-05-06
            • 2021-01-05
            • 2014-12-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多