简体   繁体   English

在C#中重复使用xml

[英]re-use of an xml in C#

i have created an xml file from my c# application i want to use the file after creation but it shows me an exception that the file is already in use?? 我已经从我的C#应用​​程序中创建了一个xml文件,我想在创建后使用该文件,但是它向我显示了该文件已被使用的例外情况?? i think i have to close the file or something.. here is the source code: 我认为我必须关闭文件或其他内容。这是源代码:

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";

} }

You need to close the Writer: 您需要关闭Writer:

 doc.Save(writer);
 writer.Close();

Or even better, enclose it in a using block: 甚至更好的是,将其包含在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);
}

The using statement will assure an exception-safe Close. using语句将确保异常安全的Close。

And use the reader in the same way. 并以相同的方式使用阅读器。

You need to dispose of your XmlTextWriter in order to close the file. 您需要处置XmlTextWriter才能关闭文件。 This is best done with a using statement: 最好using语句完成此操作:

using(XmlTextWriter writer = new XmlWriter.Create(@"D:\data.xml"))
{ 
    writer.Formatting = Formatting.Indented;
    doc.Save(writer);
}

You should use the same pattern with the reader (and in fact, any object that implements IDisposable ). 您应该与阅读器使用相同的模式(实际上,任何实现IDisposable对象)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM