Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using MemoryStream to write out to XML

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?

like image 371
Dscoduc Avatar asked Jan 28 '09 08:01

Dscoduc


2 Answers

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.

like image 107
Marc Gravell Avatar answered Oct 22 '22 06:10

Marc Gravell


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.

like image 39
Barak C Avatar answered Oct 22 '22 05:10

Barak C