Serializing POCOs into XML

I couldn't think of a suitable image, so here is a programming Dog.

I couldn’t think of a suitable image, so here is a programming Dog.

I am writing this short article as every time I need to serialize a C# object into XML I keep on forgetting how to do it (probably as I am getting old) so I thought I would post a snippet here. More for my own benefit as I am forgetful.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace HauntedHouseSoftware.SecureNotePad.DomainObjects
{
    public sealed class ApplicationSettings
    {
        public int WindowPositionX { get; set; }
        public int WindowPositionY { get; set; }
        public int WindowWidth { get; set; }
        public int WindowHeight { get; set; }
        public FormWindowState FormWindowState { get; set; }
    }
}

First lets start with a simple class that we want to serialize into XML. The class above, ApplicationSettings, was taken from my open source application SafePad. This simple class contains some window position setting that need to be serialized to XML.

To serialize this class to disk you do the following:

string path = Path.GetFullPath(AssemblyDirectory + "settings.xml");

var serializer = new XmlSerializer(settings.GetType());
using (var writer = XmlWriter.Create(path))
{
     serializer.Serialize(writer, settings);
}

To deserialize the XML back to an object you just do the following:

string path = Path.GetFullPath(AssemblyDirectory + "settings.xml");

if (File.Exists(path))
{
   var serializer = new XmlSerializer(typeof(ApplicationSettings));
   using (var reader = XmlReader.Create(path))
   {
      var settings = (ApplicationSettings)serializer.Deserialize(reader);
      return settings;
   }
}

It’s quite simple, but the next time I forget how to do it (I am blaming old age again) then I can just refer back to here. Here is the complete listing for my Settings Writer class.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;

namespace HauntedHouseSoftware.SecureNotePad.DomainObjects
{
    public sealed class SettingsWriter
    {
        private SettingsWriter()
        {
        }

        public static string AssemblyDirectory
        {
            get
            {
                return AppDomain.CurrentDomain.BaseDirectory;
            }
        }

        public static void WriteSettingsFile(ApplicationSettings settings)
        {
            if (settings == null)
            {
                return;
            }

            try
            {
                string path = Path.GetFullPath(AssemblyDirectory + "settings.xml");

                var serializer = new XmlSerializer(settings.GetType());
                using (var writer = XmlWriter.Create(path))
                {
                    serializer.Serialize(writer, settings);
                }
            }
            catch
            {
                // If this fails for any reason we don't want a crash, just bow out quetly.
                return;
            }
        }

        public static ApplicationSettings ReadSettingsFile()
        {
            try
            {
                string path = Path.GetFullPath(AssemblyDirectory + "settings.xml");

                if (File.Exists(path))
                {
                    var serializer = new XmlSerializer(typeof(ApplicationSettings));
                    using (var reader = XmlReader.Create(path))
                    {
                        var settings = (ApplicationSettings)serializer.Deserialize(reader);
                        return settings;
                    }
                }

                return null;
            }
            catch
            {
                // If this fails for any reason we don't want a crash, just bow out quetly.
                return null;
            }
        }
    }
}
Participate with Coding in the Trenches on Facebook

Participate with Coding in the Trenches on Facebook by Click the button above.

2 thoughts on “Serializing POCOs into XML

  1. Pingback: Serializing POCO’s to Byte Arrays | Stephen Haunts { Coding in the Trenches }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s