0

I have file with following content:

This line number 1
I like playing football
This is the end

I want to add the line with text just after the second line:

This line number 1
I like playing football
I like eating pasta <------ this line shall be added
This is the end

Is there any other simpler way to do so, than saving all lines (let me tell, there are n lines) to the array with n+1 elements and move them down, etc. , etc.

As a technical detail I can tell I use System.IO.StreamWriter and System.IO.File.

Search-engine on SO doesn't give results I wanted to see... C# Reference also didn't give expected result.

DidIReallyWriteThat
  • 1,033
  • 1
  • 10
  • 39
TN888
  • 7,659
  • 9
  • 48
  • 84

2 Answers2

0

You cannot insert into a file. You can append to an existing or write a new one. So you need to read it, and write it again, inserting your text on the fly where you want it.

If the file is small, you may want to use the static functions of the File class to read and write it in one step.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
0

If I understand your question, you are looking for a simpler method than resizing the array and moving every line down one? (It is not possible to insert a new line without re-writing the file)

What you can do it load the lines into a List, and insert the new line at the 2nd index by using List.Insert (Example)

Example:

List<string> lines = new List<string>();

// Read the file and add all lines to the "lines" List
using (StreamReader r = new StreamReader(file))
{
    string line;
    while ((line = r.ReadLine()) != null)
    {
       lines.Add(line);
    }
}

// Insert the text at the 2nd index
lines.Insert(2, "I like eating pasta");
Cyral
  • 13,999
  • 6
  • 50
  • 90