简体   繁体   中英

re-use of an xml in C#

i have created an xml file from my c# application i want to use the file after creation but it shows me an exception that the file is already in use?? i think i have to close the file or something.. here is the source code:

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";

}

You need to close the Writer:

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

Or even better, enclose it in a using block:

// 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);
}

The using statement will assure an exception-safe Close.

And use the reader in the same way.

You need to dispose of your XmlTextWriter in order to close the file. This is best done with a using statement:

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

You should use the same pattern with the reader (and in fact, any object that implements IDisposable ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM