Search code examples
c#serializationdeserializationbinaryformatter

Deserialize - Loading data from a file


I am using Binary Formatter to save/load data from a file. I have a library system, with two concrete classes - Users and Items - and an abstract class - Library. I am also using two lists:

List<Item> items = new List<Item>();
List<User> users = new List<User>();


public static void Serialize(object value, string path)
    {
        BinaryFormatter formatter = new BinaryFormatter();

        using (Stream fStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            formatter.Serialize(fStream, value);
        }
    }

    public static object Deserialize(string path)
    {
        if (!System.IO.File.Exists(path)) { throw new NotImplementedException(); }

        BinaryFormatter formatter = new BinaryFormatter();

        using (Stream fStream = File.OpenRead(path))
        {
            return formatter.Deserialize(fStream);
        }
    }
}

Above are the two methods that I'm using to save and load.

To call them from the Program file, I am using this code for saving:

string pathItem1 = @"itemList";
string pathUser1 = @"userList";
Library.Serialize(Library.myItems, pathItem1);
Library.Serialize(Library.myUsers, pathUser1);
Console.WriteLine("Serializing...");

and this code for loading:

string pathItem = @"itemList";
string pathUser = @"userList";
//var deserializedItem 
List<Item> items= (List<Item>)Library.Deserialize(pathItem);
//var deserializedUser = 
List<User> users = (List<User>)Library.Deserialize(pathUser);
Console.WriteLine("Deserializing...");

Saving seems to work fine. Loading however isn't. I am getting this error message:

Additional information: Unable to cast object of type 'System.Collections.Generic.List1[LibrarySystem.User]' to type 'System.Collections.Generic.List1[LibrarySystem.Item]'.

Thanks!


Solution

  • You have a strange code in your Serialize method. You are saving value parameter to both pathes: "itemList" and "userList". And actually you are not using path parameter. Your code should looks like this:

    public static void Serialize(object value, string path)
    {
        BinaryFormatter formatter = new BinaryFormatter();
    
        using (Stream fStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            formatter.Serialize(fStream, value);
        }
    }
    

    With this implementation your code will work as expected.