Rousseau Sennett

Rousseau Sennett

  • NA
  • 31
  • 43.8k

Replacing a line in a file

Jun 20 2011 8:39 AM
Hi
I am trying to find a way to:

1. Edit Data
2. Delete Data

From a file using c#
I read up online and it seems everyone's solution is to rewrite or either recreate the file without the wanted information but I doubt that is the most efficient way...and for what I'm trying to do that just wont work.

Example.
I have a text file with the following Lines
1. TEST2
2. TEST2
3. TEST3

If I want to replace Line 2 with TEST8 it's easy  by using


byte[] bytes = Encoding.UTF8.GetBytes(Environment.NewLine + "TEST8" + Environment.NewLine);
fs.Seek(XXX,SeekOrigin.Current);
fs.Write(bytes, 0, bytes.Length);
fs.Close();

But if I want to
replace it with "Testing123" it will start overriding the bytes of line 3.

Is there any way it can be done ? can I move the remaining bytes to the right to avoid the override ?
Or is there a easier way to do this ?

Also I would is I would like to completely Delete a line from the file.

Thx
Rousseau

Answers (4)