C# 逐行读取文本文件并编辑特定行

Gio*_*i19 6 c# string stringwriter stringreader

我想逐行读取文本文件并编辑特定行。因此,我将文本文件放入字符串变量中,例如:

string textFile = File.ReadAllText(filename);

我的文本文件如下:

Line A
Line B
Line C
Line abc
Line 1
Line 2
Line 3
Run Code Online (Sandbox Code Playgroud)

我有一个特定的字符串(=“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.
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想清除第三个读取行并将另一个字符串放入该行并将整个保存stringtextFile.

我怎样才能做到这一点?

wak*_*aka 5

您可以将内容存储在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);
        }
    }
}  
Run Code Online (Sandbox Code Playgroud)

然后像这样写回来:

using(var writer = new System.IO.StreamWriter(@"link\to\your\file.txt")) {
    writer.Write(sbText.ToString());
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您只是想将其存储在字符串中,textFile您可以这样做:

textFile = sbText.ToString();
Run Code Online (Sandbox Code Playgroud)