Search code examples
c#.net-4.0binary-serialization

BinaryFormatter seems to be appending rather than overwriting


I have created a load file to keep track of all characters created in a game in order. There is a 15 character limit so whenever the players creates a new character I need to check whether or not that limit was reached. However when I try to modify the object container in the load file, and serialize it again, I end up with my character index back at 0. Can anyone see my mistake?

BinaryFormatter binForm = new BinaryFormatter();

            //check load data file and add new player to the list if char limit is not reached
            using (FileStream fs = File.Open("./saves/loadData.vinload", FileMode.Open))
            {
                PlayerLoadData pLoad = (PlayerLoadData)binForm.Deserialize(fs);
                Debug.Log(pLoad.charIndex);
                if (pLoad.charIndex < 15)
                {
                    pLoad.names[pLoad.charIndex] = finalName;
                    pLoad.charIndex += 1;
                    /*
                    Debug.Log(pLoad.charIndex);
                    foreach(string n in pLoad.names)
                    {
                        Debug.Log(n);
                    }*/

                    binForm.Serialize(fs, pLoad);
                }
                else
                {
                    manifestScenePopups.TooManyChars();
                    return;
                }
            }

Solution

  • It is not related with BinaryFormatter. You should use FileMode.Create option while creating FileStream

    Specifies that the operating system should create a new file. If the file already exists, it will be overwritten

    using (FileStream fs = File.Open("d:\\temp\\a.txt", FileMode.Create))
    

    EDIT

    you should make it in 2 steps. use FileMode.Open to deserialize. then use FileMode.Create to overwrite the existing data.