替换文本文件中特定行中的单词 [英] Replace a word from a specific line in a text file
问题描述
我正在研究一个小的测试程序来测试文本文件并在其中存储一些数据,而在尝试替换特定行中的值时,我偶然发现了一个问题.
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
..依此类推.
这是我目前用来逐行读取文件的代码:
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
}
基本上,我的目标是仅在用户名匹配时才更新点数(文本行中的第二个值-infos [1]).我尝试使用以下代码(经过编辑以匹配我的信息)
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>
此问题是它将替换文本文件中的每个对应值,而不仅仅是正确行(由匹配的用户名指定)之一.我知道如何更改infos [1]的值(例如:user1为1500),但此后我不知道如何将其重写为文件.
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.
我已经在网上和StackOverflow上进行了搜索,但是对于这个特定的问题我什么都找不到,因为只有在正确的行上才可以修改该值,而不是在文本中的任何地方.
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.
非常感谢您的帮助.
推荐答案
尝试一下:
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);
这篇关于替换文本文件中特定行中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!