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 dispose of your
XmlTextWriterin order to close the file. This is best done with ausingstatement:You should use the same pattern with the reader (and in fact, any object that implements
IDisposable).