2 Replies - 1763 Views - Last Post: 19 September 2012 - 06:12 AM

#1 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1533
  • View blog
  • Posts: 5,972
  • Joined: 21-March 08

Generic Serialization Methods

Posted 05 July 2011 - 07:26 PM

Description: These two methods will serialize and deserialize ANY object to an XML file. The object could be a built in type, or a custom class that you created. It will serialize any properties that are PUBLIC.

The XML file will be formatted so that it is readable when opened in a text editor.

using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using System;

public static class XmlHelper
{
    /// <summary>
    /// Serializes the data in the object to the designated file path
    /// </summary>
    /// <typeparam name="T">Type of Object to serialize</typeparam>
    /// <param name="dataToSerialize">Object to serialize</param>
    /// <param name="filePath">FilePath for the XML file</param>
    public static void Serialize<T>(T dataToSerialize, string filePath)
    {
        try
        {
            using (Stream stream = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Default);
                writer.Formatting = Formatting.Indented;
                serializer.Serialize(writer, dataToSerialize);
                writer.Close();
            }
        }
        catch
        {
            throw;
        }
    }

    /// <summary>
    /// Deserializes the data in the XML file into an object
    /// </summary>
    /// <typeparam name="T">Type of object to deserialize</typeparam>
    /// <param name="filePath">FilePath to XML file</param>
    /// <returns>Object containing deserialized data</returns>
    public static T Deserialize<T>(string filePath)
    {
        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            T serializedData;

            using (Stream stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
            {
                serializedData = (T)serializer.Deserialize(stream);
            }

            return serializedData;
        }
        catch
        {
            throw;
        }
    }
}


Example Usage:

static void Main(string[] args)
{
    Person p = new Person() { Name = "John Doe", Age = 42 };
    XmlHelper.Serialize<Person>(p, @"D:test.xml");

    Person p2 = new Person();
    p2 = XmlHelper.Deserialize<Person>(@"D:test.xml");

    Console.WriteLine("Name: " + p2.Name);
    Console.WriteLine("Age: " + p2.Age);

    Console.Read();
}


Is This A Good Question/Topic? 0
  • +

Replies To: Generic Serialization Methods

#2 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1533
  • View blog
  • Posts: 5,972
  • Joined: 21-March 08

Re: Generic Serialization Methods

Posted 05 July 2011 - 07:26 PM

Description: static void Main(string[] args) { Person p = new Person() { Name = "John Doe", Age = 42 }; XmlHelper.Serialize(p, @"D:\test.xml"); Person p2 = new Person(); p2 = XmlHelper.Deserialize(@"D:\test.xml"); Console.WriteLine("Name: " + p2.Name); Console.WriteLine("Age: " + p2.Age); Console.Read(); }These two methods will serialize and deserialize ANY object to an XML file. The object could be a built in type, or a custom class that you created. It will serialize any properties that are PUBLIC. The XML file will be formatted so that it is readable when opened in a text editor.
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using System;

public static class XmlHelper
{
    /// 
    /// Serializes the data in the object to the designated file path
    /// 
    /// Type of Object to serialize
    /// Object to serialize
    /// FilePath for the XML file
    public static void Serialize(T dataToSerialize, string filePath)
    {
        try
        {
            using (Stream stream = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Default);
                writer.Formatting = Formatting.Indented;
                serializer.Serialize(writer, dataToSerialize);
                writer.Close();
            }
        }
        catch
        {
            throw;
        }
    }

    /// 
    /// Deserializes the data in the XML file into an object
    /// 
    /// Type of object to deserialize
    /// FilePath to XML file
    /// Object containing deserialized data
    public static T Deserialize(string filePath)
    {
        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            T serializedData;

            using (Stream stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
            {
                serializedData = (T)serializer.Deserialize(stream);
            }

            return serializedData;
        }
        catch
        {
            throw;
        }
    }
}

Was This Post Helpful? 0
  • +
  • -

#3 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1533
  • View blog
  • Posts: 5,972
  • Joined: 21-March 08

Re: Generic Serialization Methods

Posted 05 July 2011 - 07:26 PM

Description: static void Main(string[] args) { Person p = new Person() { Name = "John Doe", Age = 42 }; XmlHelper.Serialize<Person>(p, @"D:\test.xml"); Person p2 = new Person(); p2 = XmlHelper.Deserialize(@"D:\test.xml"); Console.WriteLine("Name: " + p2.Name); Console.WriteLine("Age: " + p2.Age); Console.Read(); }These two methods will serialize and deserialize ANY object to an XML file. The object could be a built in type, or a custom class that you created. It will serialize any properties that are PUBLIC. The XML file will be formatted so that it is readable when opened in a text editor.
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using System;

public static class XmlHelper
{
    /// 
    /// Serializes the data in the object to the designated file path
    /// 
    /// Type of Object to serialize
    /// Object to serialize
    /// FilePath for the XML file
    public static void Serialize(T dataToSerialize, string filePath)
    {
        try
        {
            using (Stream stream = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Default);
                writer.Formatting = Formatting.Indented;
                serializer.Serialize(writer, dataToSerialize);
                writer.Close();
            }
        }
        catch
        {
            throw;
        }
    }

    /// 
    /// Deserializes the data in the XML file into an object
    /// 
    /// Type of object to deserialize
    /// FilePath to XML file
    /// Object containing deserialized data
    public static T Deserialize(string filePath)
    {
        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            T serializedData;

            using (Stream stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
            {
                serializedData = (T)serializer.Deserialize(stream);
            }

            return serializedData;
        }
        catch
        {
            throw;
        }
    }
}

Was This Post Helpful? 0
  • +
  • -

#4 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1533
  • View blog
  • Posts: 5,972
  • Joined: 21-March 08

Re: Generic Serialization Methods

Posted 05 July 2011 - 07:26 PM

Description: Added instructions to bottom of snippet.These two methods will serialize and deserialize ANY object to an XML file. The object could be a built in type, or a custom class that you created. It will serialize any properties that are PUBLIC. The XML file will be formatted so that it is readable when opened in a text editor.
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using System;

public static class XmlHelper
{
    /// 
    /// Serializes the data in the object to the designated file path
    /// 
    /// Type of Object to serialize
    /// Object to serialize
    /// FilePath for the XML file
    public static void Serialize(T dataToSerialize, string filePath)
    {
        try
        {
            using (Stream stream = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Default);
                writer.Formatting = Formatting.Indented;
                serializer.Serialize(writer, dataToSerialize);
                writer.Close();
            }
        }
        catch
        {
            throw;
        }
    }

    /// 
    /// Deserializes the data in the XML file into an object
    /// 
    /// Type of object to deserialize
    /// FilePath to XML file
    /// Object containing deserialized data
    public static T Deserialize(string filePath)
    {
        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            T serializedData;

            using (Stream stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
            {
                serializedData = (T)serializer.Deserialize(stream);
            }

            return serializedData;
        }
        catch
        {
            throw;
        }
    }
}

=================================
Example usage
=================================
// the snippet "instructions" won't seem to update, so I will put the example code here

static void Main(string[] args)
{
    Person p = new Person() { Name = "John Doe", Age = 42 };
    XmlHelper.Serialize(p, @"D:test.xml");

    Person p2 = new Person();
    p2 = XmlHelper.Deserialize(@"D:test.xml");

    Console.WriteLine("Name: " + p2.Name);
    Console.WriteLine("Age: " + p2.Age);

    Console.Read();
}

Was This Post Helpful? 0
  • +
  • -

#5 CharlieMay  Icon User is offline

  • This space intentionally left blank
  • member icon

Reputation: 1726
  • View blog
  • Posts: 5,704
  • Joined: 25-September 09

Re: Generic Serialization Methods

Posted 19 September 2012 - 06:10 AM

In the example you have in the instructions for Deserialize, this gives an error: The type arguments for method 'XMLHelper.Deserialize<T>(string)' cannot be inferred from the usage. Try specifying the type arguments explicitly. I had to use Person p2 = new Person(); p2 = XmlHelper.Deserialize<person>(@"D:\test.xml");
Was This Post Helpful? 0
  • +
  • -

#6 CharlieMay  Icon User is offline

  • This space intentionally left blank
  • member icon

Reputation: 1726
  • View blog
  • Posts: 5,704
  • Joined: 25-September 09

Re: Generic Serialization Methods

Posted 19 September 2012 - 06:12 AM

that's supposed to read p2 = XmlHelper.Deserialize<person>(@"D:\test.xml");
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1