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

26.5k views Asked by At

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?

4

There are 4 answers

4
waka On BEST ANSWER

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();
2
AudioBubble On

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.

2
Feras Al Sous On

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);
}
0
live-love On

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