0

I'm making a small game and I'm having trouble saving the result of the game into a text file. I have tried reading only the needed line but with little success:

List<string> a = File.ReadLines(path).Skip(2).Take(2).ToList();

Text file has 4 lines inside it:

PlayerTag
Wins: 0
Losses: 0
Draws: 0

After the player wins I want increase the amount of wins by 1.

What would be the ideal way to do this?

Jawad
  • 11,028
  • 3
  • 24
  • 37
rocs
  • 33
  • 3
  • Read **all** the lines, change the one you want to change, then write all the lines to the text file? – stuartd Dec 29 '19 at 02:07
  • Read in the entire file, deserialize, update, serialize and save – Jawad Dec 29 '19 at 02:07
  • 1
    `var lines = File.ReadAllLines(path); int oldWins = int.Parse(lines[1].Split(": ")[1]); oldWins += 1; lines[1] = "Wins: " + oldWins.ToString(); File.WriteAllLines(path, lines);` – CodingYoshi Dec 29 '19 at 02:12
  • 1
    I suggest you look at JSON serialisation/deserialisation. So much easier than parsing your own text files. https://dotnetfiddle.net/Pd43a6 – andrew Dec 29 '19 at 02:29
  • Write a simple **custom class** to encapsulate your player score history, then use the [XmlSerializer](https://learn.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlserializer?view=netframework-4.8). – Idle_Mind Dec 29 '19 at 02:41

1 Answers1

0

With the current format, you could do the following.

var str = File.ReadAllLines(filePath);
str[WinPosition] = Update(str[WinPosition]);
File.WriteAllLines(filePath);

Where WinPosition is a constant defined as

const int WinPosition = 1;
const int LossesPosition = 2;
const int DrawsPosition = 3;

And Update is defined as

private string Update(string source)
{
    var data = source.Split(':');
    data[1] = (Int32.Parse(data[1])+1).ToString();
    return string.Join(":",data);
}

The Update method would read the string, split it based on the delimiter (":") and then update the numeric part. Together, the constants and common update method would allow you to update Losses and Draws in the same way as Wins (and perhaps more readable than using 1/2/3 indices directly).

str[LossesPosition] = Update(str[LossesPosition]);
str[Draws] = Update(str[Draws]);

Having said so, If you have the option changing the format of the file, I would suggest you opt for Json or Xml. This would be a better approach than using the current format.

Anu Viswan
  • 17,797
  • 2
  • 22
  • 51