Search code examples
c#streamreaderstreamwriter

C# Using StreamWriter, append a string in a specific line


I want to manipulate a file with C# and StreamReader/StreamWriter. Initially, I need to find some specific lines and then append a string after them. Using this code, I can locate the lines that I want to write after them.

            string[] targetValues = {"firstTargetValue"};

            List<int> nlines = new List<int>();
            string[] newValues = {"firstNewValue" };

            int j = 1; //1-based indexing
            StreamReader sr = new StreamReader(filepath);
            string line = sr.ReadLine();

            while (line != null)
            {

                line = sr.ReadLine();
                j++;

                if (line == targetValues[0])
                {
                    nlines.Add(j);
                }
            } 
            sr.Close();

So right now I am having the line number ( j=5 ). For the last part, I want to write my string after this line and not at the end of the file.

            var sw = new StreamWriter(filepath,true);

            sw.WriteLine(newValues[0]);
            sw.Close();

Can I somehow use the j that has the line number and achieve my goal?

Text example:

Initial File

1
2
3
4
firstTargetValue
6
7
8

Desired file

1
2
3
4
firstTargetValue
firstNewValue
6
7
8

Thanks in advance, I was not able to find an answer that fits me


Solution

  • It can be a possible solution:

    var input = File.ReadAllLines(filepath);
    var output = new List<string>();
    
    foreach (var line in input)
    {
        output.Add(line);
    
        if (line == "firstTargetValue")
        {
            output.Add("firstNewValue");
        }
    }
    
    output.ForEach(line => Console.WriteLine(line));