I have noticed two different approaches to writing out data to an XML file (error handling omitted for brevity).
The first method has you build the XML document and then simply save the XML to a file:
using (XmlWriter writer = XmlWriter.Create(fileName))
{
writer.WriteStartDocument(true);
writer.WriteStartElement("parentelement");
writer.WriteEndElement();
writer.WriteEndDocument();
}
The second method has you create a MemoryStream, and then save the MemoryStream to a file:
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
MemoryStream ms = new MemoryStream();
using (XmlWriter writer = XmlWriter.Create(ms, settings))
{
writer.WriteStartDocument(true);
writer.WriteStartElement("parentelement");
writer.WriteEndElement();
writer.WriteEndDocument();
}
using (FileStream fs = File.Open(fileName, FileMode.Create, FileAccess.Write))
{
ms.WriteTo(fs);
ms.Dispose();
}
I'm guessing the logic for using a MemoryStream is to ensure the XML file can be built before trying to save the file. Would the the MemoryStream method provide for an Atomic write event and/or protect against write issues while you are adding entries into the XML file?
Can anyone explain if this is actually necessary or just an overkill way to add unnecessary lines of code to my project?
The MemoryStream
version is wasteful on this occasion. MemoryStream
is useful if you want to perform Stream
-like work, but don't want an actual file. If you are writing a file, then just write to the file. This avoids the need to buffer all the data in memory.
It is true that the memory stream approach is wasteful for simple operations but it is very useful for cases such as saving the xml as encrypted file, as compressed file etc.
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