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.