c# - 在 C# 中重用 xml

标签 c# xml

我已经从我的 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/

相关文章:

java - 具有顶部和底部边距的自定义按钮

c# - HttpClient GetAsync 和 ReadAsStringAsync 需要反序列化复杂 JSON 响应的一部分

C# 从 HTTP 响应保存文件

c# - 如果第一个代码正在执行,如何等待?

php - 使用Youtube的XML从视频中获取标签

xml - 使用系统 xsd 对 xml 进行离线验证

c# - 如何更改 DatagridView 中的标题文本 - 在代码 C# 中?

c# - 数据过滤的设计模式

xml 元素作为对象 HTMLCollection 返回

Python 值错误 : XPath error: Unregistered function