简体   繁体   English

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

[英]C# Read text file line by line and edit specific line

I want to read a text file line by line and edit a specific line.我想逐行读取文本文件并编辑特定行。 So, I have put the text file into a string variable like:因此,我已将文本文件放入一个字符串变量中,例如:

string textFile = File.ReadAllText(filename);

My text file is like:我的文本文件是这样的:

Line A
Line B
Line C
Line abc
Line 1
Line 2
Line 3

I have a specific string (="abc"), which I want to search in this textFile.我有一个特定的字符串 (="abc"),我想在这个 textFile 中搜索它。 So, I am reading the lines until find the string and going to the third line ("Line 3" -> this line is always different) after that found string:所以,我正在阅读这些行,直到找到字符串并在找到的字符串之后转到第三行(“第 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.
        }
    }
}

I want to clear the third read line and put another string to this line and save the whole string into textFile .我想清除第三个读取行并将另一个字符串放入该行并将整个string保存到textFile

How can I do this?我该怎么做?

You can store the contents in a StringBuilder like this:您可以将内容存储在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);
        }
    }
}  

and then write it back like this:然后像这样写回:

using(var writer = new System.IO.StreamWriter(@"link\to\your\file.txt")) {
    writer.Write(sbText.ToString());
}

Or if you simply want to store it in the string textFile you can do it like this:或者,如果您只是想将它存储在字符串textFile您可以这样做:

textFile = sbText.ToString();

Write the whole file again would be easier:再次写入整个文件会更容易:

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

You will probably want something like the following:您可能需要类似以下内容:

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

This way you will be reading the text file line by line until the end of the document and if the value is picked up it will be replace by your new value.通过这种方式,您将逐行读取文本文件,直到文档结束,如果该值被选中,它将被您的新值替换。

Here is a full example:这是一个完整的例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM