0

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.

PotatoBox
  • 583
  • 2
  • 10
  • 33

1 Answers1

2
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);
    }

}
CSharpYouDull
  • 229
  • 1
  • 4
  • Thanks, works like charm. There is one more thing that I'll write if someone was looking for answer in future: after creating new file you must close it, otherwise you won't be able to load it until restart of the application. Simply add "file.Close();" before "return;". – PotatoBox Jul 19 '13 at 18:45
  • 1
    And the `using() {}` block does the `Close()`. – H H Jul 19 '13 at 19:06