繁体   English   中英

System.IO.IOException错误,无法访问该文件

[英]System.IO.IOException error, can't get access to the file

我无法理解问题在哪里,尽管事实上,这个代码很容易。

我有这样的功能:

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错误,进程无法访问该文件,因为它正被另一个进程使用。 怎么可能得到这样的错误?

尝试

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

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

你是打开它的过程!

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

XDocument.Save将创建该文件 - 您不必:

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

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

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

正如其他答案所述,您没有关闭输出文件。 使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM