Possible Duplicate:
Editing a text file in place through C#
I need to replace a line in a very big file , so I don’t want to readAll and writeAll – I want to get to the line requiring replacement , replace , and close the file.
Any idea how to do it in C#?
Thanks!
Really, you’ve two options, the first has some severe restrictions, the second is the simplest and probably the one you want.
read the file line by line,
remembering the position of the
current line you’ve just read
(StreamReader.BaseStream.pos). If
this is the line to replace and
the new line is exactly the same
length as the old, seek back to
the start of the line and write.
to new file, don’t write the line to
be replaced, but write the new line
instead. Then just keep reading &
writing until done.
The second option is much simpler and could well be faster (you’d need to profile to be sure), and it doesn’t have the new line is exactly the same length as the old restriction.
Go with option 2
P.S. Get out of the habit of using
ReadAllWriteAllfunctions, they’re not good for real world applications. The “read a line, process a line” idiom will work on files of 100k and 100TB equally well . . . the 100TB file will obviously take a little longer 🙂P.P.S While Option 1 sounds straight forward, it’s actually surprising difficult to implement correctly, there are 100’s of little things that can go wrong. Variable byte sizes, different encodings etc. Option 2 is as simple as it sounds.