Replace a word from a specific line in a text file

2019-01-29 11:39发布

问题:

I'm working on a little test program to experiment with text files and storing some data in them, and I've stumbled accross a problem when trying to replace a value in a specific line.

This is how the formatting of my text file is done :

user1, 1500, 1
user2, 1700, 17

.. and so on.

This is the code I am using at the moment to read the file line by line :

string line;
Streamreader sr = new Streamreader(path);

while ((line = sr.ReadLine()) != null)
{
   string[] infos = line.Split(',');
   if (infos[0] == username) //the username is received as a parameter (not shown)
      //This is where I'd like to change the value
}

Basically, my objective is to update the number of points (the second value in the text line - infos[1]) only if the username matches. I tried using the following code (edited to match my informations)

string text = File.ReadAllText("test.txt");
text = text.Replace("some text", "new value");
File.WriteAllText("test.txt", text);</pre>

The problem with this is that it will replace every corresponding value in the text file, and not just the one of the correct line (specified by the matching username). I know how to change the value of infos[1] (ex: 1500 for user1) but I don't know how to rewrite it to the file after that.

I've searched online and on StackOverflow, but I couldn't find anything for this specific problem where the value is only to be modified if it's on the proper line - not anywhere in the text.

I run out of ideas on how to do this, I would really appreciate some suggestions.

Thank you very much for your help.

回答1:

Try this:

var path = @"c:\temp\test.txt";
var originalLines = File.ReadAllLines(path);

var updatedLines = new List<string>();
foreach (var line in originalLines)
{
    string[] infos = line.Split(',');
    if (infos[0] == "user2")
    {
        // update value
        infos[1] = (int.Parse(infos[1]) + 1).ToString();
    }

    updatedLines.Add(string.Join(",", infos));
}

File.WriteAllLines(path, updatedLines);


回答2:

use ReadLines and LINQ:

var line = File.ReadLines("path")
               .FirstOrDefault(x => x.StartsWith(username));

if (line != null)
{
     var parts = line.Split(',');
     parts[1] = "1500"; // new number
     line = string.Join(",", parts);
     File.WriteAllLines("path", File.ReadLines("path")
         .Where(x => !x.StartsWith(username)).Concat(new[] {line});
}


标签: c# text replace