簡體   English   中英

在C#中重復使用xml

[英]re-use of an xml in C#

我已經從我的C#應用​​程序中創建了一個xml文件,我想在創建后使用該文件,但是它向我顯示了該文件已被使用的例外情況?? 我認為我必須關閉文件或其他內容。這是源代碼:

private void button1_Click(object sender, EventArgs e)
{
    // Create the XmlDocument. 
    XmlDocument doc = new XmlDocument();
    doc.LoadXml("<item><name>salman</name></item>"); //Your string here 

    // Save the document to a file and auto-indent the output. 
    XmlTextWriter writer = new XmlTextWriter(@"D:\data.xml", null);
    writer.Formatting = Formatting.Indented;
    doc.Save(writer);
    ///////////////

    XmlDataDocument xmlDatadoc = new XmlDataDocument();
    xmlDatadoc.DataSet.ReadXml(@"D:\data.xml");// here is the exception!!!!!

    //now reading the created file and display it in grid view

    DataSet ds = new DataSet("Books DataSet");
    ds = xmlDatadoc.DataSet;
    dataGridView1.DataSource = ds.DefaultViewManager;
    dataGridView1.DataMember = "CP";

}

您需要關閉Writer:

 doc.Save(writer);
 writer.Close();

甚至更好的是,將其包含在using塊中:

// Save the document to a file and auto-indent the output. 
using (XmlTextWriter writer = new XmlTextWriter(@"D:\data.xml", null))
{
   writer.Formatting = Formatting.Indented;
   doc.Save(writer);
}

using語句將確保異常安全的Close。

並以相同的方式使用閱讀器。

您需要處置XmlTextWriter才能關閉文件。 最好using語句完成此操作:

using(XmlTextWriter writer = new XmlWriter.Create(@"D:\data.xml"))
{ 
    writer.Formatting = Formatting.Indented;
    doc.Save(writer);
}

您應該與閱讀器使用相同的模式(實際上,任何實現IDisposable對象)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM