尝试使用以下代码段替换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,声称该文件已被其他进程打开。
答案 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);
如果您在同一范围内处理多个一次性实体(并非罕见),则可避免深度嵌套。 :)