替换文本文件中特定行的单词

我正在开发一个小测试程序来试验文本文件并在其中存储一些数据,当我尝试替换特定行中的值时,我遇到了一个问题。

这就是我的文本文件格式化的方式:

user1, 1500, 1 user2, 1700, 17 

.. 等等。

这是我目前用来逐行读取文件的代码:

 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 } 

基本上,我的目标是仅在用户名匹配时更新点数(文本行中的第二个值 – 信息[1])。 我尝试使用以下代码(编辑以匹配我的信息)

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

这样做的问题是它将替换文本文件中的每个相应值,而不仅仅是正确行中的一个(由匹配的用户名指定)。 我知道如何更改infos [1]的值(例如,对于user1为1500),但我不知道如何将其重写到文件中。

我在网上和StackOverflow上搜索过,但是我找不到任何针对这个特定问题的内容,如果它只是在正确的行上而不是在文本的任何地方修改。

我没有关于如何做到这一点的想法,我真的很感激一些建议。

非常感谢您的帮助。

试试这个:

 var path = @"c:\temp\test.txt"; var originalLines = File.ReadAllLines(path); var updatedLines = new List(); 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); 

使用ReadLinesLINQ

 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}); }