using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Common.Extensions
{
/// <summary>
/// Contains the logic for streaming extensions.
/// </summary>
public static class StreamExtensions
{
/// <summary>
/// Serialize an object.
/// </summary>
/// <typeparam name="T">The type of the object that gets serialized.</typeparam>
/// <param name="stream">The stream to which the bytes will be written.</param>
/// <param name="serializableObject">The object that gets serialized.</param>
public static void SerializeObject<T>(this Stream stream, T serializableObject) where T : IXmlSerializable
{
var writerSettings = new XmlWriterSettings();
writerSettings.Indent = true;
writerSettings.IndentChars = " "; // 4 spaces
writerSettings.Encoding = Encoding.UTF8;
using (var xmlWriter = XmlWriter.Create(stream, writerSettings))
{
serializableObject.WriteXml(xmlWriter);
}
stream.Close();
}
/// <summary>
/// Deserialize a stream and return the object.
/// </summary>
/// <typeparam name="T">The type of the object that returns from the deserialization.</typeparam>
/// <param name="stream">The stream which contains the bytes to deserialize.</param>
/// <returns>The object recovered.</returns>
public static T DeserializeObject<T>(this Stream stream) where T : IXmlSerializable
{
using (var xmlTextReader = XmlReader.Create(stream))
{
var serializer = new XmlSerializer(typeof(T));
T result = (T)serializer.Deserialize(xmlTextReader);
stream.Close();
return result;
}
}
}
}
I have made a class which can serialize a generic object which implements the interface IXmlSerializable
and can deserialize an xml file to that same object. The idea behind this is as follows: we are using a lot of xml files to (for example) write configurations to. Since the configuration classes are often different we needed a generic function to create and read the xml files.
The stream we use (atm) is a file stream since it is currently only used for reading and writing the xml files to and from disk. Later we might use other kind of streams as well.
I am wondering if what I have written is the correct way (obviously it works but can it be made better? )