serialize/deserialize a list of objects using BinaryFormatter

betaFlux picture betaFlux · Oct 15, 2014 · Viewed 12.7k times · Source

I know there were already many discussions on that topic, like this one:

BinaryFormatter and Deserialization Complex objects

but this looks awfully complicated. What I'm looking for is an easier way to serialize and deserialize a generic List of objects into/from one file. This is what I've tried:

    public void SaveFile(string fileName)
    {
        List<object> objects = new List<object>();

        // Add all tree nodes
        objects.Add(treeView.Nodes.Cast<TreeNode>().ToList());

        // Add dictionary (Type: Dictionary<int, Tuple<List<string>, List<string>>>)
        objects.Add(dictionary);

        using(Stream file = File.Open(fileName, FileMode.Create))
        {
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(file, objects);
        }
    }

    public void LoadFile(string fileName)
    {
        ClearAll();
        using(Stream file = File.Open(fileName, FileMode.Open))
        {
            BinaryFormatter bf = new BinaryFormatter();

            object obj = bf.Deserialize(file);

            // Error: ArgumentNullException in System.Core.dll
            TreeNode[] nodeList = (obj as IEnumerable<TreeNode>).ToArray();

            treeView.Nodes.AddRange(nodeList);

            dictionary = obj as Dictionary<int, Tuple<List<string>, List<string>>>;

        }
    }

The serialization works, but the deserialization fails with an ArgumentNullException. Does anyone know how to pull the dictionary and the tree nodes out and cast them back, may be with a different approach, but also nice and simple? Thanks!

Answer

Daniel J.G. picture Daniel J.G. · Oct 15, 2014

You have serialized a list of objects where the first item is a list of nodes and the second a dictionary. So when deserializing, you will get the same objects back.

The result from deserializing will be a List<object>, where the first element is a List<TreeNode> and the second element a Dictionary<int, Tuple<List<string>, List<string>>>

Something like this:

public static void LoadFile(string fileName)
{
    ClearAll();
    using(Stream file = File.Open(fileName, FileMode.Open))
    {
        BinaryFormatter bf = new BinaryFormatter();

        object obj = bf.Deserialize(file);

        var objects  = obj as List<object>;
        //you may want to run some checks (objects is not null and contains 2 elements for example)
        var nodes = objects[0] as List<TreeNode>;
        var dictionary = objects[1] as Dictionary<int, Tuple<List<string>,List<string>>>;
        
        //use nodes and dictionary
    }
}

You can give it a try on this fiddle.