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

标签 c# string stringreader stringwriter

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

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/

相关文章:

c# - 如何在 C# 中使用反射来列出 .asmx 的方法

c# - WPF - MVVM 文本框限制为特定字符

c++ - 我对下面的代码有两个问题

python - 如何删除重复的连续字符并使用正则表达式保留第一个字符?

Java-将多行字符串写入文件

java - 如何使用 Java 中的 stringreader 获取字符串中的下一个字符?

c# - C#代码中{0}\\{1}的含义

c# - 如何使用 C# 处理 CSV 文件中的换行符?

c# - 如何在 C# 中生成一个包含 3 个字母和 6 个数字的随机字母数字数组?

c# - 如何将 StringReader 中的位置重置为 String 的开头?