Replacing a line in a file "in place" - C# [duplicate]
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 r开发者_如何学Goequiring 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.
- 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.
- 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 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 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.
Short answer: you dont.
It will be much easier and faster to just read from one file and write to another.
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.
精彩评论