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)
You're overwritting the file as you save it to filename
.
To backup the old copy,
filename.bak
) before saving and
delete it afterwards or
filename.new
) and rename it on successWhen an exception is thrown, you can easily restore the old/previous version of the xml file.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With