[英]re-use of an xml in C#
我已经从我的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";
}
您需要关闭Writer:
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语句将确保异常安全的Close。
并以相同的方式使用阅读器。
您需要处置XmlTextWriter
才能关闭文件。 最好using
语句完成此操作:
using(XmlTextWriter writer = new XmlWriter.Create(@"D:\data.xml"))
{
writer.Formatting = Formatting.Indented;
doc.Save(writer);
}
您应该与阅读器使用相同的模式(实际上,任何实现IDisposable
对象)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.