Click here to Skip to main content
15,884,739 members
Articles / Programming Languages / C#

Custom Serialization Example

Rate me:
Please Sign up or sign in to vote.
4.36/5 (9 votes)
9 Jan 2008CPOL10 min read 97.4K   1.2K   39  
An example of implementing custom serialization, how to serialize a collection, and using a File Serialization utility class
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Permissions;
using System.Windows.Forms;

namespace MyUtilities
{

    public static class FileSerializer
    {
        public static void Serialize( string filename, object objectToSerialize )
        {
            if (objectToSerialize == null)
                throw new ArgumentNullException("objectToSerialize cannot be null");
            Stream stream = null;
            try
            {
                stream = File.Open(filename, FileMode.Create);
                BinaryFormatter bFormatter = new BinaryFormatter();
                bFormatter.Serialize(stream, objectToSerialize);
            }
            finally
            {
                if (stream != null)
                    stream.Close();
            }
        }

        public static T Deserialize<T>( string filename )
        {
            T objectToSerialize = default(T);
            Stream stream = null;
            try
            {
                stream = File.Open(filename, FileMode.Open);
                BinaryFormatter bFormatter = new BinaryFormatter();
                objectToSerialize = (T)bFormatter.Deserialize(stream);
            }
            catch (Exception err)
            {
                MessageBox.Show("The application failed to retrieve the inventory - " + err.Message);               
            }
            finally
            {
                if (stream != null)
                    stream.Close();
            }
            return objectToSerialize;
        }
    }

}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions