簡體   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