How to insert or remove bytes from the middle of a large file in .NET.

Is it possible to effectively insert or remove bytes from the middle of a large file, and if so, how? Or am I stuck overwriting the entire file after the data has been inserted or deleted?

[A lot of Bytes][Unwanted Bytes][A lot of Bytes] - > [A lot of Bytes][A lot of Bytes] or [A lot of Bytes][A lot of Bytes] - > [A lot of Bytes][New Inserted Bytes][A lot of Bytes] 
+6
c # file-io
source share
4 answers

The most effective way is to search for the position where you want to paste the element, read everything to the end, paste a new element and copy the rest.

The problem is not in the language, but in how the data is stored on the medium, where everything is just a long sequence of bits. You can imagine this as a single strip of paper with the data recorded in a pen. If you want to insert something, you have to drop everything that comes afterwards. Of course, if you have a lot of free space between data blocks, you can insert your things there (which is the idea of ​​Sparse Files), but this is hardly convenient.

+4
source share

It is impossible to insert data or delete data in O (1) in C #, nor C ++, nor in any language with standard APIs or class libraries.

The best thing you could do is to have some kind of file format that you yourself define, it can support O (1) installs and uninstalls. But you probably have to deal with fragmentation.

Perhaps you can also take a look at an SQL database such as sqlite, which will take care of the complexities for you.

+2
source share

If it is a flat file, you should rewrite the part after editing. If it is a file with a logical structure (for example, pointers to other parts of the file), then updates can be very effective.

+1
source share

You need to copy the file. At best, you can leave using Sparse Files , but only if the "Many Bytes" are zeros.

0
source share

All Articles