views:

66

answers:

3

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!

+2  A: 

Short answer: you dont.

It will be much easier and faster to just read from one file and write to another.

leppie
Unless you know the lines are of the same byte length, yeah...
Noldorin
Maybe he does not have enought computing resources available to do that.
Aurélien Ribon
...which is even less likely if you're using a variable length encoding like Unicode.
Noldorin
@Aurelien: With this method you can make your buffer size as small as you like, there's no resources issue.
Noldorin
+6  A: 

Really, you've two options, the first has some severe restrictions, the second is the simplest and probably the one you want.

  1. Open the file for Read Write access, 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.
  2. Open the file, read each line, 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 will very nearly be as fast, 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 ReadAll WriteAll functions, 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.

Binary Worrier
Thanks. I can make it the same size , but maybe it's an overkill. I'll go for the basic solution and we'll see how far it takes me
yossale
A: 

If your new string has same length as old, you can write it to corresponding place of file. If it is shorter, you could "hack" this by expanding it with spaces... But if its longer, you have to rewrite file from that position to end (beginning of file stays the same). On the other hand, if part you have to replace is very big, it is indeed faster to stream replaced file into another one.

alxx
I don't like the "hack it by overwriting with spaces" suggestion one bit, actually. Even if it would be "functionally correct" (or it wouldn't matter too much) in this specific instance, which we just don't know... -1
peSHIr
it's only an idea for question author.
alxx