Search code examples
c#binaryformatter

Binary Serializer not working except for first time


Why would this code only work when it's called for the first time(adds the first element). In the consequent calls, the file stays the same, containing only one user

        public void AddUser(User user)
    {
        FileStream stream = new FileStream(PATH_TO_LOGINS, FileMode.OpenOrCreate);
        BinaryFormatter formatter = new BinaryFormatter();
        List<User> users=new List<User>();
        if (stream.Length > 0)
            users = (List<User>) formatter.Deserialize(stream);
        users.Add(user);
        formatter.Serialize(stream,users);
        stream.Close();
    }

Solution

  • Add stream.Position = 0 before you perform the serialization. That way you start writing from the very beginning of the file when you serialize it.

    If you don't set it to 0 you'll start writing from the end of the file and forward, since it's where the FileStream's position currently is after you performed the deserialization.

    users.Add(user);
    stream.Position = 0;
    formatter.Serialize(stream,users);