我已经从我的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";}
发布于 2010-11-21 22:18:51
您需要清除XmlTextWriter才能关闭该文件。这最好使用using语句来完成:
using(XmlTextWriter writer = new XmlWriter.Create(@"D:\data.xml"))
{
writer.Formatting = Formatting.Indented;
doc.Save(writer);
}您应该对阅读器使用相同的模式(实际上,任何实现IDisposable的对象)。
发布于 2010-11-21 22:17:43
您需要关闭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语句将确保异常安全关闭。
并以同样的方式使用阅读器。
https://stackoverflow.com/questions/4238276
复制相似问题