我已经从我的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";
}
答案 0 :(得分:8)
你需要关闭作家:
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语句将确保异常安全关闭。
以同样的方式使用阅读器。
答案 1 :(得分:2)
您需要处置XmlTextWriter
才能关闭文件。最好使用using
语句:
using(XmlTextWriter writer = new XmlWriter.Create(@"D:\data.xml"))
{
writer.Formatting = Formatting.Indented;
doc.Save(writer);
}
您应该使用与阅读器相同的模式(事实上,任何实现IDisposable
的对象)。