C# Read text file line by line and edit specific line

Giovanni19 picture Giovanni19 · Aug 30, 2017 · Viewed 17.2k times · Source

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. 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:

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.

How can I do this?

Answer

waka picture waka · Aug 30, 2017

You can store the contents in a StringBuilder like this:

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