1

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;
                }
            }
Jaja
  • 51
  • 8

1 Answers1

2

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.

EZI
  • 15,209
  • 2
  • 27
  • 33
  • Tried that but I get an exception: SerializationException: serializationStream supports seeking, but its length is 0 [EDIT] Also, I check the file beforehand to ensure it exists and contains the base object container. If it does not exist, it is created. – Jaja Apr 04 '15 at 22:34
  • @Jaja you should make it in 2 steps. use `FileMode.Open` to deserialize. then use `FileMode.Create` to overwrite the existing data. – EZI Apr 04 '15 at 22:36
  • Thank you, I used another using statement for serializing and that worked. – Jaja Apr 04 '15 at 22:43