BinaryFormatter: SerializationException

陌路散爱 提交于 2019-12-11 19:33:33

问题


I'm using BinaryFormatter to load & save my treeView. I want to prevent errors if destination file doesn't exist. My code:

        public static void Load(TreeView tree, string filename)
    {
        if (!File.Exists(filename))
        {
            Stream file = File.Create(filename);
            return;
        }
        else
        {

            using (Stream file = File.Open(filename, FileMode.Open))
            {
                BinaryFormatter bf = new BinaryFormatter();
                object obj = bf.Deserialize(file);

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

If I'll manually delete file, it should create new file, called same as previous one. The problem is that when it reaches object obj = bf.Deserialize(file);, error appears Attempting to deserialize an empty stream.. My guess is that the new file is missing some binary structures or something, but still I'm not sure how to solve it. And if I'll try to add node to the treeView and save it later, I'm getting error that file is used by other program.


回答1:


public static void Load(TreeView tree, string filename)
{
    using (var file = File.Open(filename, FileMode.OpenOrCreate))
    {
        if (file.Length.Equals(0))
            return;

        var bf = new BinaryFormatter();
        var obj = bf.Deserialize(file);
        var nodeList = (obj as IEnumerable<TreeNode>).ToArray();
        tree.Nodes.AddRange(nodeList);
    }

}


来源:https://stackoverflow.com/questions/17753118/binaryformatter-serializationexception

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