Posts By Category

Posts By Date

Resources:

C# Books
ASP.NET Books DotNet4All








If you like to support this site, feel free to make a donation to support improvements.

Thank you!

Monetize Your Blog

Using StreamReader & StreamWriter to insert a text at a given line number

System.IO.StreamWriter 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:

o ns = "urn:schemas-microsoft-com:office:office" /?>

1. Orange

2. Banana

<---- Want to Insert: 3. Apple

4. Grapefruit

5. Kiwi

And say you want to insert the text "3. Apple" 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 = "myFile.txt";

            int iInsertAtLineNumber = 2;

            string strTextToInsert = "3. Apple";

            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. 

kick it on DotNetKicks.com

Feedback

Posted on 11/10/2009 6:27:32 AM

"Niptech - Is there a way changing a line without rewriting the all file "
Same what he said?

Posted on 5/27/2009 3:40:00 PM

Is there a way changing a line without rewriting the all file ?

Posted on 6/18/2007 2:19:29 AM

great article..thank you

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 


Copyright © 2007 Yousef Mannaa. All material on this site is copyrighted.
Do not publish or reproduce any of this material without written permission from the Author