Reputation: 565
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";
}
Upvotes: 1
Views: 179
Reputation: 273274
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.
Upvotes: 8
Reputation: 499072
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
).
Upvotes: 2