我已经从我的 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
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);
}
using 语句将确保异常安全的关闭。
并以同样的方式使用阅读器。
关于c# - 在 C# 中重用 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4238276/