How to insert text at a specified line of a file using C#

To file related operations its better to use System.IO.StreamWriter. Because it allows you to write text to a file easily if you are creating the file and know the order of the lines. However, what if you are trying to edit a file? For example, you need to insert a text at a specified line number in an existing text file.
Say you have a text file that contains:


Jaganathan

Ammu

<---- Want to Insert: Amudha

Bhathrinath

Amuranji

And say you want to insert the text "Amudha" between line 2 & 4, how do you do that in C#?

One way is to load the file into an ArrayList, with each item representing a line, then you can insert your text in the desired location using the ArrayList.Insert function, then use the StreamWriter to rewrite the file to disk from the array with each item written on a separate line.

The code below shows how to do this task:

using System;

using System.IO;

using System.Collections;

 

namespace InsertLineInTextFile

{

    class Program

    {

        static void Main (string[] args)

        {

            string strTextFileName = "file.txt";

            int iInsertAtLineNumber = 2;

            string strTextToInsert = "Amudha";

            ArrayList lines = newArrayList();

            StreamReader rdr = newStreamReader(

                strTextFileName);

             string line;

            while ((line = rdr.ReadLine()) != null)

                lines.Add(line);

            rdr.Close();

            if (lines.Count > iInsertAtLineNumber)

                lines.Insert(iInsertAtLineNumber,

                   strTextToInsert);

            else

                lines.Add(strTextToInsert);

            StreamWriter wrtr = newStreamWriter(

                strTextFileName);

            foreach (string strNewLine in lines)

                wrtr.WriteLine(strNewLine);

            wrtr.Close();

        }

    }

}

There might be a better way to do this, but this should do a quick solution for now.