serialize/deserialize a list of objects using BinaryFormatter

醉酒当歌 提交于 2019-12-23 20:19:47

问题


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!


回答1:


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(byte[] bytes)
{
    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.



来源:https://stackoverflow.com/questions/26383711/serialize-deserialize-a-list-of-objects-using-binaryformatter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!