保存xml文件时防止文件损坏

wal*_*ter 4 .net c#

当抛出OutOfMemoryException时,下一行有时会破坏xml文件并创建零长度xml.如何防止文件损坏?

xmlDoc.Save(filename)
Run Code Online (Sandbox Code Playgroud)

保存 - 抛出"System.OutOfMemoryException"类型的异常.在System.IO.StreamWriter.Write(Char值)处的System.IO.StreamWriter.Flush(布尔flushStream,布尔flushEncoder)处保存System.IO.FileStream.Write(Byte []数组,Int32偏移量,Int32计数) System.Xml.XmlTextWriter.WriteStartElement上的System.Xml.XmlTextWriter.WriteStartElement(String prefix,String localName,String ns)中System.Xml.XmlTextWriter.AutoComplete(Token token)的System.Xml.XmlTextWriter.Indent(Boolean beforeEndElement)(在System.Xml的System.Xml.XmlElement.WriteTo(XmlWriter w)的System.Xml.XmlElement.WriteContentTo(XmlWriter w)的System.Xml.XmlElement.WriteTo(XmlWriter w)处的字符串前缀,String localName,String ns). System.Xml.XmlDocument.WriteTo(XmlWriter w)中的XmlDocument.WriteContentTo(XmlWriter xw)位于MainOptions.Save的System.Xml.XmlDocument.Save(String filename)(String filename,ItemOptions options)

Mat*_*ten 6

在保存文件时,您将覆盖该文件filename.要备份旧副本,

  • 它移动到另一个位置(如filename.bak保存之前),之后将其删除
  • 将新文件另存为另一个文件(如filename.new),并在成功时重命名

抛出异常时,您可以轻松恢复xml文件的旧版/早期版.