我想逐行读取文本文件并编辑特定的一行。因此,我将文本文件放入一个字符串变量中,如:
string textFile = File.ReadAllText(filename);
我的文本文件如下:
Line A
Line B
Line C
Line abc
Line 1
Line 2
Line 3
我有一个特定的字符串(="abc"(,我想在这个文本文件中搜索它。所以,我一直在读这些行,直到找到字符串,然后转到找到字符串后的第三行("line 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(@"linktoyourfile.txt")) {
writer.Write(sbText.ToString());
}
或者,如果你只是想把它存储在字符串textFile
中,你可以这样做:
textFile = sbText.ToString();
您可能想要以下内容:
DirectoryInfo di = new DirectoryInfo(Location);
FileInfo[] rgFiles = di.GetFiles("txt File");
foreach (FileInfo fi in rgFiles)
{
string[] alllines = File.ReadAllLines(fi.FullName);
for (int i = 0; i < alllines.Length; i++)
{
if (alllines[i].Contains(stringToSearch))
{
alllines[i] = alllines[i].Replace(stringToSearch, some value );
}
}
}
这样,您将逐行读取文本文件,直到文档结束,如果值被提取,它将被新值替换。
重新编写整个文件会更容易:
string old = "abc";
string nw = "aa";
int counter = 0;
using(StreamWriter w = new StreamWriter("newfile")
{
foreach(string s in File.ReadLines(path))
w.WriteLine(s == old ? nw : s);
}
下面是一个完整的例子:
using System;
using System.IO;
namespace rename
{
class Program
{
static void Main(string[] args)
{
// Fix files, replace text
DirectoryInfo di = new DirectoryInfo(@"C:tempall");
FileInfo[] rgFiles = di.GetFiles("*");
foreach (FileInfo fi in rgFiles)
{
string[] alllines = File.ReadAllLines(fi.FullName);
for (int i = 0; i < alllines.Length; i++)
{
if (alllines[i].StartsWith("00:"))
{
// Edit: Replace these lines with an empty line
alllines[i] = alllines[i].Replace(alllines[i], "");
}
}
// Rewrite new files in the folder
File.WriteAllLines(@"C:tempnew" + fi.Name, alllines);
}
}
}
}