System.IO.IOException错误,不能访问该文件 [英] System.IO.IOException error, can't get access to the file
问题描述
我不明白的地方的问题是,尽管事实上,这段代码很容易
I can't understand where problem is, despite the fact, that this code pretty easy.
我有这样的功能:
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.Text
, Gen_Peroid.Text
和 Alg_Perioad.Text
是字符串
这是我如何使用这个功能:
This is how I use this function:
File.Create(@"C:\ProgramData\RadiolocationQ\Q.xml");
WriteToDoc(@"C:\ProgramData\RadiolocationQ\Q.xml");
它创建的文件,但没有被写在该文件中。所以确切的错误 System.IO.IOException
错误的方法,不能因为它正被另一个进程访问文件。这怎么可能得到这样的错误?
It creates file, but nothing was written in that file. So the exact error System.IO.IOException
error, The process cannot access the file because it is being used by another process. How is it possible to get such error?
推荐答案
至于其他的答案的状态,你不关闭你的输出文件。使用LinqToXML保存XML文件的正确方法是:
As the other answers state, you are not closing your output file. The proper way of saving XML files using LinqToXML is:
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
如果没有必要的。
This releases the file & stream. You can omit the XmlWriterSettings
if not needed.
这篇关于System.IO.IOException错误,不能访问该文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!