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

C#逐行读取文本文件并编辑特定行,c#,string,stringreader,stringwriter,C#,String,Stringreader,Stringwriter,我想逐行读取文本文件并编辑特定的行。因此,我将文本文件放入一个字符串变量中,如: string textFile=File.ReadAllText(文件名) 我的文本文件如下所示: Line A Line B Line C Line abc Line 1 Line 2 Line 3 我有一个特定的字符串(=“abc”),我想在这个文本文件中搜索它。因此,我一直在读这些行,直到找到字符串,然后转到找到的字符串之后的第三行(“第3行”->这一行总是不同的): string line = ""; s

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

string textFile=File.ReadAllText(文件名)

我的文本文件如下所示:

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 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);
}

您可能需要以下内容:

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 );
        }
    }
}
DirectoryInfo di=新的DirectoryInfo(位置);
FileInfo[]rgFiles=di.GetFiles(“txt文件”);
foreach(rgFiles中的FileInfo-fi)
{
字符串[]alllines=File.ReadAllLines(fi.FullName);
for(int i=0;i

通过这种方式,您将逐行读取文本文件,直到文档结束,如果提取了该值,它将替换为新值

您可以将内容存储在
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 = sbText.ToString();
然后像这样写回去:

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 = sbText.ToString();
或者,如果您只想将其存储在字符串
textFile
中,您可以这样做:

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 = sbText.ToString();

以下是一个完整的示例:

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);
            }
        }
    }
}
使用系统;
使用System.IO;
名称空间重命名
{
班级计划
{
静态void Main(字符串[]参数)
{
//修复文件,替换文本
DirectoryInfo di=newdirectoryinfo(@“C:\temp\all\”);
FileInfo[]rgFiles=di.GetFiles(“*”);
foreach(rgFiles中的FileInfo-fi)
{
字符串[]alllines=File.ReadAllLines(fi.FullName);
for(int i=0;i
这可能会有所帮助:。使用此方法,循环遍历所有行,替换要替换的行,然后只写回原始文件。现在,行
abc
被替换,这不是OP想要的。另外,<<代码>使用< /COD>必须是小写的,必须有括号,并且如果(Foo= value)不能做<代码>,因为它不会评估到BoL(并且在某些语言中,如C++会改变<代码> FoO < /代码>的值,并导致奇怪的错误)。您必须使用
if(foo==value)
。另外,
nw
是一个可怕的变量名。为什么不
newValue
或者一些描述性的东西呢?非常感谢!这似乎是正确的方法。现在,我唯一的问题是将字符串写回“textFile”字符串时出错。以下行的“路径中的非法字符:
使用(var writer=new System.IO.StreamWriter(textFile)){
@Giovanni19:我的错误,“textFile”应该是“链接到您要写入的文本文件”。我发现您在帖子中使用了不同的变量。如果您只是想将其作为字符串存储在
textFile
中,您可以使用:
textFile=sbText.ToString()
。我已更新了答案。谢谢。但这是在包含字符串“abc”的行中添加新行。我想在字符串“abc”后的第三行添加新行。@Giovanni19:我已经更新了答案。现在它应该可以像您希望的那样工作了。;)这不是我想要的:/请参阅我的第一篇文章。@Giovanni19,您想逐行阅读文档并更新值(如果找到),然后您想更新此值吗?我是对的?上面的代码将适用于…您想保存此文档的新版本吗?