在C#中重用xml

sal*_*man 1 c# xml

我已经从我的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";
Run Code Online (Sandbox Code Playgroud)

}

Hen*_*man 8

你需要关闭作家:

 doc.Save(writer);
 writer.Close();
Run Code Online (Sandbox Code Playgroud)

或者甚至更好,将它包含在一个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);
}
Run Code Online (Sandbox Code Playgroud)

using语句将确保异常安全的Close.

并以相同的方式使用阅读器.