C# – add an empty line inside text file

.netc++stringtext

So let me give you an example of how my file could look:

Hello
my
name
is

Now, for example, I want to go through the different lines of this file with System.IO.File.ReadAllLines(); and then check with a loop whether the current line has the word "my" in it (so the second line in this case).

As my next step, I want to add a new line right after "my", so it looks like this:

Hello
my

name
is

I approached this with 2 methods now. I was hoping File.Append(); would offer a method where I could append anything after it has found the string I am looking for, but obviously it only offers methods to append strings to the end of files.

My second approach was to read in all the lines with string[] test=System.IO.File.ReadAllLines();
and then iterate through all the lines, checking each line with

for (int i = 0; i < (test.Length - 1); i++)
{
    if(test[i].Contains("my"))
    {
        test[i] = test[i] + Environment.NewLine;
    }
}

and then write all this back in the file with System.IO.File.WriteAllLines();

The problem I am facing here is the fact that this command does not really add a real new line to the file, as I've checked test.Length before and after, and both time I got 4 as a result.

Best Solution

Another option is to add the lines to a List which would give you the Insert() method: *Only use this for relatively small files.

Something like:

        string path = @"c:\some\path\file.txt";
        List<String> lines = new List<string>(System.IO.File.ReadAllLines(path));
        for (int i = 0; i < lines.Count; i++)
        {
            if (lines[i].Contains("my"))
            {
                if (i < lines.Count -1)
                {
                    lines.Insert(i + 1, "");
                }
                else
                {
                    lines.Add("");
                }
            }
        }
        System.IO.File.WriteAllLines(path, lines.ToArray());