Deserialization of MemoryStream via BinaryFormatter

5.4k views Asked by At

didn't find a solution to following problem.
I had a working code for saving/loading a TreeView in a file but I want to save it to Properties.Settings.Default.

Unfortunately I get the error "no map for object" in this line:

object obj = bf.Deserialize(ms);

Here is the complete code for (de)serialization:
Don't know how to solve this one. :(

public static void SaveTreeView(TreeView tree)
{
    using (MemoryStream ms = new MemoryStream())
    {
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(ms, tree.Nodes.Cast<TreeNode>().ToList());
        ms.Position = 0;
        var sr = new StreamReader(ms);
        Properties.Settings.Default.tree = sr.ReadToEnd();
        Properties.Settings.Default.Save();
    }
}

public static void LoadTreeView(TreeView tree)
{

    using (MemoryStream ms = new MemoryStream())
    {
        var sw = new StreamWriter(ms);
        sw.WriteLine(Properties.Settings.Default.tree);
        sw.Flush();
        ms.Seek(0, SeekOrigin.Begin);

        BinaryFormatter bf = new BinaryFormatter();
        object obj = bf.Deserialize(ms);

        TreeNode[] nodeList = (obj as IEnumerable<TreeNode>).ToArray();
        tree.Nodes.AddRange(nodeList);
    }
}

Anybody got an idea?
Thanks is advance.

1

There are 1 answers

3
PCG On BEST ANSWER

Try this out

    public static void SaveTree(TreeView tree)
    {
        using (var ms = new MemoryStream())
        {
            new BinaryFormatter().Serialize(ms, tree.Nodes.Cast<TreeNode>().ToList());

            Properties.Settings.Default.tree = Convert.ToBase64String(ms.ToArray());
            Properties.Settings.Default.Save();
        }
    }

    public static void LoadTree(TreeView tree)
    {
        byte[] bytes = Convert.FromBase64String(Properties.Settings.Default.tree);
        using (var ms = new MemoryStream(bytes, 0, bytes.Length))
        {
            ms.Write(bytes, 0, bytes.Length);
            ms.Position = 0;
            var data =  new BinaryFormatter().Deserialize(ms);
            tree.Nodes.AddRange(((List<TreeNode>)data).ToArray());
        }
    }