Wednesday, December 24, 2008

.NET Object Serialization and Deserialization

#region using
using System;
using System.Xml.Serialization;
using System.IO;
#endregion using

namespace Utilities
{
// Serializes and deserializes objects into and from xml document.
public static class Serializer
{
#region Public Methods

// Serializes the supplied object into specified xml document.
public static void SerializeObject( string fileName, T objectToSerialize )
{
using ( TextWriter writer = new StreamWriter( fileName ) )
{
XmlSerializer serializer = new XmlSerializer( typeof( T ) );
serializer.Serialize( writer, objectToSerialize );
}
}

// Deserializes the specified object from supplied xml document.
public static T DeserializeObject( string fileName )
{
// Create object to be deserialized.
T objectToDeserialize = (T)Activator.CreateInstance( typeof(T) );

if ( File.Exists( fileName ) )
{
// Deserialize object from xml file.
using ( TextReader reader = new StreamReader( fileName ) )
{
XmlSerializer serializer = new XmlSerializer( typeof(T) );
objectToDeserialize = (T)serializer.Deserialize( reader );
}
}

return objectToDeserialize;
}

#endregion Public Methods
}
}

No comments:

Post a Comment