Search code examples
c#streamreaderstreamwriter

Save to file broken - C#


I try to use a txt file as a backup: when a checkbox is activated, we add 1 in a "victory" txt file and when it is deactivated we add 1 in a "loose" txt file, and here is my problem: For example if the checkbox is disabled, I run the script and I get 1 in "loose" and 0 in "victory", so normal; but if I run it again (without changing anything), I get 51 in "loose" and 49 in "victory", but I would like to get 2 and 0.. I don't know if it's really clear;

here is the piece of code:

if (Directory.Exists("C:/PekmiIndustries/BrokenGame"))
{
    TextReader VtxtR = new StreamReader("C:/PekmiIndustries/BrokenGame/Victory.txt");
    TempVReadStr = VtxtR.Read().ToString();
    VRead = Convert.ToInt32(TempVReadStr);
    VRead += 1;
    if (VictoireCheck.Checked == true)
    {
        VRead += 1;
    }
    VtxtR.Close();
    TextWriter VtxtW = new StreamWriter("C:/PekmiIndustries/BrokenGame/Victory.txt");
    VtxtW.Write(VRead.ToString());
    VtxtW.Close();

    TextReader LtxtR = new StreamReader("C:/PekmiIndustries/BrokenGame/Loose.txt");
    TempLReadStr = LtxtR.Read().ToString();
    LRead = Convert.ToInt32(TempLReadStr);
    LRead += 1;
    if (VictoireCheck.Checked == false)
    {
        LRead += 1;
    }
    LtxtR.Close();
    TextWriter LtxtW = new StreamWriter("C:/PekmiIndustries/BrokenGame/Loose.txt");
    LtxtW.Write(LRead.ToString());
    LtxtW.Close();

    MessageBox.Show("Les stats ont correctement étés sauvegardées !", "BrokenGame");
}
else
{
    MessageBox.Show("Err Sauvegarde - Dossier; \nRéessaie de sauvegarder les stats, ou de redémarrer BrokenGame", "BrokenGame");
}

Solution

  • Read reads a single character, not a string. The numeral representation of ASCII 1 is 49. Add 2 to that (which you do on every read since you add 1 regardless of the state of the checkbox) makes 51 be written back to one file.

    0 is represented by numeral 48, which you add 1 to and then write back - thus 49.

    You should take a look at StreamReader.ReadLine as reading the first character only would mean that when you've run the program 10 times, for either victory or loss, it would overflow back to 1 again, not 10.