Home > C#

Serializing and Deserializing XML to files

7. April 2009

This is a simple class for serializing a type to a file and deserializing a type from a file. This code shouldn’t be considered production, but it will show you a very simple way to do it.

    /// <summary>
    /// Class for saving xml serializable types 
    /// to a file.
    /// </summary>
    /// <typeparam name="T">The generic serializable
    /// type that is going to be serialized or deserialized</typeparam>
    public class TypeSerializer<T>
    {
        /// <summary>
        /// Serializes and saves the specified item
        /// to a file specified.
        /// </summary>
        /// <param name="item">The item to serialize.</param>
        /// <param name="path">The path to the file.</param>
        public void Save(T item, string path)
        {
            // Create the serializer
            XmlSerializer s = new XmlSerializer(typeof(T));
            // Create the writer
            TextWriter w = new StreamWriter(path);
            // Do the work
            s.Serialize(w, item);
            // Clean up
            w.Close();
        }

        /// <summary>
        /// Loads the specified file and serializes it.
        /// </summary>
        /// <param name="path">The path to the item.</param>
        /// <returns>The serialized type.</returns>
        public T Load(string path)
        {
            // Create the serializer
            XmlSerializer s = new XmlSerializer(typeof(T));
            // The item we are returning
            T item;
            // The text reader that puts the text in the stream
            TextReader r = new StreamReader(path);
            // Deserialize the item and cast it
            item = (T)s.Deserialize(r);
            // Clean up
            r.Close();
            // return the item
            return item;
        }
    }
Simple to use. Just call new TypeSerializer<YourClass>().Save(item, path); to save it or TypeSerializer<YourClass>().Load(path); to load it. Thank you CodeProjectfor the step in the right direction. I just wanted a simpler example to start people out. I hope this helps.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

C# , ,

Comments

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading