System.IO : Inserting a Text in between

G

Guest

Hi,
I have a file in which I want to insert a text in between say the a specific
line.
Basically, I want to read through the file and search for a particular line
or character and then once I find this line or character I am searching for I
want to Insert a new string in a new line below the Line I was searching for.

Any examples on how to acheive this?

Line #1
Line #2
Line #3
Line #4
Line #5
Line #6

Search for Line #3, when found Insert a new line below it to look like this.

Line #1
Line #2
Line #3
NEW LINE INSERTES!!!
Line #4
Line #5
Line #6
 
H

Helge Jensen

Sam said:
Any examples on how to acheive this?

You will need to open a temporary file and write to that, then
afterwards do some replacing.

Below is some code to get you started, beware that the code have
line-ending problems and may add a newline to the end-of-file if none
exists, but it will get you started.

static void add_line(
TextReader from, TextWriter to,
string after, string add)
{
for ( string line = from.ReadLine();
line != null;
line = from.ReadLine() )
{
to.WriteLine(line);
if ( line.LastIndexOf(after) != -1 )
to.WriteLine(add);
}
}
static void add_line(string path, string after, string add)
{
string tmp_path = string.Format("{0}.tmp", path);
using ( TextWriter w = new StreamWriter(File.OpenWrite(tmp_path)))
using ( TextReader r = new StreamReader(File.OpenRead(path)))
add_line(r, w, after, add);
// This way to replace is *not* atomic,
// but i don't know any other way that works on win32
File.Delete(path);
File.Move(tmp_path, path);
}
 
G

Guest

If you don't want to read the entire file into memory first then I'd follow
on from Helge Jensen response above.

If you are already reading in the entire file (e.g. using
StreamReader.ReadToEnd()) then I'd just use a regular expression to find and
add the new line.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top