替换文本文件中特定行中的单词
本文关键字:单词 文本 文件 替换 | 更新日期: 2023-09-27 17:57:10
我正在开发一个小的测试程序来试验文本文件并在其中存储一些数据,在尝试替换特定行中的值时偶然发现了一个问题。
这是我的文本文件的格式化方式:
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
}
基本上,我的目标是仅在用户名匹配时才更新点数(文本行中的第二个值 - infos[1])。我尝试使用以下代码(编辑以匹配我的信息)
string text = File.ReadAllText("test.txt");
text = text.Replace("some text", "new value");
File.WriteAllText("test.txt", text);</pre>
这样做的问题是它将替换文本文件中的每个相应值,而不仅仅是正确行中的值(由匹配的用户名指定)。我知道如何更改 infos[1] 的值(例如:user1 为 1500),但我不知道之后如何将其重写为文件。
我已经在网上和 StackOverflow 上搜索过,但我找不到这个特定问题的任何内容,其中值只有在正确的行上时才要修改 - 而不是文本中的任何位置。
我对如何做到这一点没有想法,我将非常感谢一些建议。
非常感谢您的帮助。
试试这个:
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);
使用 ReadLines
和 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});
}