views:

4615

answers:

6

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?

A: 

You do not have to use a MemoryStream to use the XmlWriter. The XmlWriter can directly write to a file; you can use another overload of the XmlWriter.Create method, which takes a filename as an argument, or instead of writing to a MemoryStream, you could also write to an XmlTextWriter or a FileStream.

So, you 2nd codesnippet could be written as:

using( FileStream fs = ... )
{
    XmlWriter writer = XmlWriter.Create (fs);
}

AFAIK, the XmlWriter will not protect you from creating a non-wellformed Xml.

Frederik Gheysels
Thanks for the answer... Both methods in my question work, without a doubt... I just wanted to try and get some clarification on whether I should use the MemoryStream or not.
Dscoduc
XmlWriter will protectec you and enforce well formed xml except: 1) if you use WriteDocType or WriteRaw 2) if you stop early - i.e. do not close all the elements to the root element at the end
ShuggyCoUk
Thank you for the clarification...
Dscoduc
+5  A: 

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.

Marc Gravell
+1  A: 

This is overkill and a waste.

The two key approaches are based on

  1. You do not know the full structure of the document until the end.
  2. As you 'create' the parts of the document you know that they are the final form of this part of the document.

the first requires the creation of an in memory model of the document (for which the DOM is model is designed). Once you're finished with it simply writing directly to the file stream is fine.

The second allows you to save considerable memory and complexity and simply use XmlWriter which can point directly to the end stream (in this case a file stream).

At no stage is it necessary to use a MemoryStream

ShuggyCoUk
A: 

If you (for some reason) want to ensure the XmlWriter succeedes (i.e. otherwise the file might be truncated, but in most cases this will be due to - as mentioned - not closing tags) you can use a temporary file stream, fx something similar to this:

public class TempFileStream : FileStream
{

    public TempFileStream(Action<string> onClose)
        : base(Path.GetTempFileName(), FileMode.OpenOrCreate, FileAccess.ReadWrite)
    {
        this.CloseDelegate = onClose;
    }

    protected Action<string> CloseDelegate 
    {
        get;
        set;
    }

    public override void Close()
    {
        base.Close();
        if (File.Exists(this.Name))
        {
            this.CloseDelegate(this.Name);
        }
    }

}

The used like:

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;

using (TempFileStream tfs = new TempFileStream(f => File.Move(f, filename))
using (XmlWriter writer = XmlWriter.Create(tfs, settings))
{
    writer.WriteStartDocument(true);
    writer.WriteStartElement("parentelement");
    writer.WriteEndElement();
    writer.WriteEndDocument();
}

This won't consume a lot of memory (of course it only makes/makes more sense when the resulting XML is large)

veggerby
+1  A: 

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.

Barak C
A: 

I think that using a memory stream would be useful if creating the document in a web app or web service. The file location may conflict with another process that could be running the same processing which might cause invalid results. In a memory stream the processing should be segregated.

Rich