如何在C#.NET中替换现有XML文件的内容?

时间:2009-01-15 11:07:12

标签: c# .net xml file locking

尝试使用以下代码段替换C#.NET中的XML文件内容时:

string file = Path.GetTempFileName(); // pretend this is a real file
string tmpFile = Path.GetTempFileName();

using (var writer = XmlWriter.Create(File.Create(tmpFile)))
{
    writer.WriteStartElement("root");
    for (int i = 0; i < 100; i++)
    {
        writer.WriteElementString("test", null, 
            "All work and no play makes Jack a dull boy");
    }
    writer.WriteEndElement();
}

File.Delete(file);
File.Move(tmpFile, file);

...我收到一个System.IO.IOException,声称该文件已被其他进程打开。

2 个答案:

答案 0 :(得分:7)

由于某种原因,XmlWriter类显然没有为临时文件配置底层流。将流放在其自己的“using”子句中可确保正确关闭流。将代码更改为

string file = Path.GetTempFileName(); // pretend this is a real file
string tmpFile = Path.GetTempFileName();

using (var stream = File.Create(tmpFile))
using (var writer = XmlWriter.Create(stream))
{
    writer.WriteStartElement("root");
    for (int i = 0; i < 100; i++)
    {
        writer.WriteElementString("test", null, 
            "All work and no play makes Jack a dull boy");
    }
    writer.WriteEndElement();
}                
File.Delete(file);
File.Move(tmpFile,file);

...使IOException消失,并按预期工作。

答案 1 :(得分:4)

可以链接使用语句。稍微修改您的代码:

string file = Path.GetTempFileName(); // pretend this is a real file
string tmpFile = Path.GetTempFileName();

using (var stream = File.Create(tmpFile))
using (var writer = XmlWriter.Create(stream))
{
    writer.WriteStartElement("root");
    for (int i = 0; i < 100; i++)
    {
        writer.WriteElementString("test", null, 
            "All work and no play makes Jack a dull boy");
    }
    writer.WriteEndElement();
}                
File.Delete(file);
File.Move(tmpFile,file);

如果您在同一范围内处理多个一次性实体(并非罕见),则可避免深度嵌套。 :)