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

Upvotes: 0

Views: 1971

Answers (4)

Majid Shahabfar
Majid Shahabfar

Reputation: 4829

Another workaround can be replacing the targetValue with (targetvale + newValue)

using System.IO;
    
public void InsertToFile(string[] targetValues) 
{
    string filePath = "filePath";
    var text = File.ReadAllText(filePath); 
    foreach (var target in targetValues)
        text.Replace(target, $"{target} new value to be inserted");
    File.WriteAllText(filePath, text);
}

Upvotes: 1

Majid Shahabfar
Majid Shahabfar

Reputation: 4829

You cannot rewrite a line without rewriting the entire file. If the file is small then reading the entire content into memory and then writing it out again might make sense.

using System.IO;
using System.Linq;
    
public void InsertToFile(string[] targetValues) 
{
    string filePath = "filePath";
    var txtLines = File.ReadAllLines(filePath).ToList();
    foreach (var target in targetValues)
    {
        txtLines.Insert(txtLines.IndexOf(target), "//new line to be inserted");
    }
    File.WriteAllLines(filePath, txtLines);
}

Upvotes: 1

Viktor T&#246;r&#246;k
Viktor T&#246;r&#246;k

Reputation: 1319

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

Upvotes: 1

GI1
GI1

Reputation: 126

You can’t do that with a StreamWriter, but...Why not use another stream writer to write out the contents of the old file up to the line where you want to insert a new one and after write the rest of the existing file? Then just use File’s static methods to delete the old one and rename the new as the old.

Upvotes: 3

Related Questions