Is it possible to write to the middle of a file using Filestream in C#

Wanting to know if it is possible to insert text into the middle of a file using FileStream in .NET/C#. If not, is there another way of doing it? I see the option of Truncate and Append, but obviously that isn't what I'm looking for. I suppose I could open a filestream source, create another destination file and write to it as I see fit, then truncate the source and write back to it from the second file or a large buffer, or delete the source and rename the destination file to the original source filename.

I guess my question is, how is this kind of thing most efficiently and safely done.

Jon Skeet
people
quotationmark

No - this is fundamentally a limitation of most file systems.

I would recommend the approach you're suggesting (selective copying from the original file to a new file) but then just rename the files rather than copying back over the top of the original.

If you're happy to have the whole file in memory, you can follow the comment in the question and read the whole file into memory, make the change and then overwrite the existing file - but obviously that doesn't scale as well to very large files. It all depends on the context.

people

See more on this question at Stackoverflow