首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在C#中重用xml

在C#中重用xml
EN

Stack Overflow用户
提问于 2010-11-21 22:14:13
回答 2查看 167关注 0票数 1

我已经从我的c#应用程序创建了一个xml文件,我想在创建后使用该文件,但它向我显示了一个例外,即该文件已在使用中。我想我得关闭这个文件或者别的什么..源代码如下:

代码语言:javascript
复制
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";

}

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-11-21 22:18:51

您需要清除XmlTextWriter才能关闭该文件。这最好使用using语句来完成:

代码语言:javascript
复制
using(XmlTextWriter writer = new XmlWriter.Create(@"D:\data.xml"))
{ 
    writer.Formatting = Formatting.Indented;
    doc.Save(writer);
}

您应该对阅读器使用相同的模式(实际上,任何实现IDisposable的对象)。

票数 2
EN

Stack Overflow用户

发布于 2010-11-21 22:17:43

您需要关闭Writer:

代码语言:javascript
复制
 doc.Save(writer);
 writer.Close();

或者更好的方法是,将其封装在using块中:

代码语言:javascript
复制
// 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语句将确保异常安全关闭。

并以同样的方式使用阅读器。

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4238276

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档