【发布时间】:2017-08-30 10:31:28
【问题描述】:
我想逐行读取文本文件并编辑特定行。因此,我将文本文件放入了一个字符串变量中,例如:
string textFile = File.ReadAllText(filename);
我的文本文件是这样的:
Line A
Line B
Line C
Line abc
Line 1
Line 2
Line 3
我有一个特定的字符串 (="abc"),我想在这个 textFile 中搜索它。所以,我正在阅读这些行,直到找到字符串并在找到的字符串之后转到第三行(“第 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中。
我该怎么做?
【问题讨论】:
-
这可能会有所帮助:File.ReadAllLines。使用这个,遍历所有行,替换你想要替换的那一行,然后写回原始文件。
标签: c# string stringreader stringwriter