我想逐行阅读文本文件并编辑特定的行。所以,我把文本文件放到一个字符串变量中,如:
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
。
我该怎么做?
答案 0 :(得分:2)
您可以将内容存储在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();
答案 1 :(得分:1)
这是一个完整的例子:
using System;
using System.IO;
namespace rename
{
class Program
{
static void Main(string[] args)
{
// Fix files, replace text
DirectoryInfo di = new DirectoryInfo(@"C:\temp\all\");
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:\temp\new\" + fi.Name, alllines);
}
}
}
}
答案 2 :(得分:0)
再次写完整个文件会更容易:
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);
}
答案 3 :(得分:0)
您可能需要以下内容:
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 );
}
}
}
通过这种方式,您将逐行读取文本文件,直到文档结束,如果值被拾取,则将替换为新值。