尝试使用如下代码段替换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,声称该文件已被另一个进程打开.
由于某种原因,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消失,它按预期工作.