我正在嘗試編輯 xml 檔案。
但是document.Save()方法必須使用另一個檔案名。
有沒有辦法使用相同的檔案?或其他方法。謝謝!
string path = "test.xml";
using (FileStream xmlFile = File.OpenRead(path))
{
XDocument document = XDocument.Load(xmlFile);
var setupEl = document.Root;
var groupEl = setupEl.Elements().ElementAt(0);
var valueEl = groupEl.Elements().ElementAt(1);
valueEl.Value = "Test2";
document.Save("test-result.xml");
// document.Save("test.xml"); I want to use this line.
}
我收到錯誤:
該行程無法訪問檔案“[...]\test.xml”,因為它正被另一個行程使用。
uj5u.com熱心網友回復:
問題是您在檔案仍然打開的情況下嘗試寫入檔案。但是,一旦加載了 XML 檔案,就無需打開它。只需更精細地確定代碼范圍即可解決問題:
string path = "test.xml";
XDocument document;
using (FileStream xmlFile = File.OpenRead(path))
{
document = XDocument.Load(xmlFile);
}
// the rest of your code
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/481530.html
上一篇:如何在c#中將文本框轉換為int
