System.IO.IOException错误,无法访问该文件
我无法理解问题在哪里,尽管事实上,这个代码非常简单。
我有这样的function:
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
是string
。
这是我使用此function的方式:
File.Create(@"C:\ProgramData\RadiolocationQ\Q.xml"); WriteToDoc(@"C:\ProgramData\RadiolocationQ\Q.xml");
它创建文件,但该文件中没有写入任何内容。 所以确切的错误System.IO.IOException
错误,进程无法访问该文件,因为它正被另一个进程使用。 怎么可能得到这样的错误?
正如其他答案所述,您没有关闭输出文件。 使用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
。
尝试
System.IO.File.Create(@"C:\ProgramData\RadiolocationQ\Q.xml").Close();
编辑:Reinhards答案更好。 我只是关闭File.Create()流,它锁定文件,但没有必要。
你是打开它的过程!
不要先调用File.Create
– 它会使文件流保持打开状态,并且您无法覆盖该文件。
XDocument.Save
将创建该文件 – 您不必:
将此XDocument序列化为文件,覆盖现有文件(如果存在)。
如果一个文件不存在, XDocument.Save将创建一个文件。 File.Create()
不需要
File.Create()
没有关闭,它正在锁定你的文件。