我想逐行读取文本文件并编辑特定行。因此,我已将文本文件放入一个字符串变量中,例如:
string textFile = File.ReadAllText(filename);
我的文本文件是这样的:
Line A
Line B
Line C
Line abc
Line 1
Line 2
Line 3
我有一个特定的字符串 (="abc"),我想在此文本文件中搜索它。因此,我正在阅读这些行,直到找到字符串并转到找到的字符串之后的第三行(“第 3 行”-> 这一行总是不同的):
string line = "";
string stringToSearch = "abc";
using (StringReader reader = new StringReader(textFile))
{
while ((line = reader.ReadLine()) != null)
{
if (line.Contains(stringToSearch))
{
line = reader.ReadLine();
line = reader.ReadLine();
line = reader.ReadLine();
//line should be cleared and put another string to this line.
}
}
}
我想清除读取的第三行并将另一个字符串放入该行并将整个string
保存到textFile
中。
我该怎么做?
最佳答案
您可以像这样将内容存储在 StringBuilder
中:
StringBuilder sbText = new StringBuilder();
using (var reader = new System.IO.StreamReader(textFile)) {
while ((line = reader.ReadLine()) != null) {
if (line.Contains(stringToSearch)) {
//possibly better to do this in a loop
sbText.AppendLine(reader.ReadLine());
sbText.AppendLine(reader.ReadLine());
sbText.AppendLine("Your Text");
break;//I'm not really sure if you want to break out of the loop here...
}else {
sbText.AppendLine(line);
}
}
}
然后像这样写回去:
using(var writer = new System.IO.StreamWriter(@"link\to\your\file.txt")) {
writer.Write(sbText.ToString());
}
或者,如果您只是想将它存储在字符串 textFile
中,您可以这样做:
textFile = sbText.ToString();
关于C#逐行读取文本文件并编辑特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45958061/