Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent file corruption when saving xml file

Tags:

c#

.net

Next line sometimes is corrupting xml file and creating a zero length xml, when OutOfMemoryException has been thrown. How to prevent file corruption?

xmlDoc.Save(filename)

Save-Exception of type 'System.OutOfMemoryException' was thrown. Save-at System.IO.FileStream.Write(Byte[] array, Int32 offset, Int32 count) at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder) at System.IO.StreamWriter.Write(Char value) at System.Xml.XmlTextWriter.Indent(Boolean beforeEndElement) at System.Xml.XmlTextWriter.AutoComplete(Token token) at System.Xml.XmlTextWriter.WriteStartElement(String prefix, String localName, String ns) at System.Xml.XmlDOMTextWriter.WriteStartElement(String prefix, String localName, String ns) at System.Xml.XmlElement.WriteTo(XmlWriter w) at System.Xml.XmlElement.WriteContentTo(XmlWriter w) at System.Xml.XmlElement.WriteTo(XmlWriter w) at System.Xml.XmlDocument.WriteContentTo(XmlWriter xw) at System.Xml.XmlDocument.WriteTo(XmlWriter w) at System.Xml.XmlDocument.Save(String filename) at MainOptions.Save(String filename, ItemOptions options)

like image 677
walter Avatar asked Jan 18 '23 22:01

walter


2 Answers

You're overwritting the file as you save it to filename. To backup the old copy,

  • move it to another location (like filename.bak) before saving and delete it afterwards or
  • save the new file as another file (like filename.new) and rename it on success

When an exception is thrown, you can easily restore the old/previous version of the xml file.

like image 104
Matten Avatar answered Jan 28 '23 07:01

Matten


Agree with Matten. Alternative solution can be generating xml string before saving it to a file:

Using ms As New MemoryStream
    xmlDoc.Save(ms)
    Using outStream As FileStream = File.Open(filename,
                 FileMode.Create, FileAccess.Write, FileShare.Read)
        ms.WriteTo(outStream)
    End Using
End Using

Use stream to match xmlDoc.Save(filename)

like image 22
walter Avatar answered Jan 28 '23 09:01

walter