Reputation: 8721
I need to do some operations in the middle of a binary file (change string value, boolean or int32) and leave everything else as it was. How can I quickly skip items I don't need to work with and get right to what I need without processing every binary object (there are many of them and it's slow)?
Upvotes: 0
Views: 449
Reputation: 2135
There is a Seek function in the Stream, perhaps, you may just Seek to the position you want to change and then use the Write method to modify the file? You may encounter problems, however, if you need to add bytes in the middle rather than just to replace them -- in such a case you would need to rewrite the rest of the file (in order to offset the existing content).
Upvotes: 0
Reputation: 1503599
This entirely depends on the structure of your file. Indeed, whether or not you can change a value will depend on the structure of the file - if you need to make a change which would make the file larger or smaller, you're likely to need to create a new file, as you can't just insert or delete bytes from the middle of a file.
If your file has a fixed-length record format, you can skip to the right place by seeking, e.g. using the Stream.Position
property. If your file doesn't have a fixed-length format, you may need to process everything fully. An "in-between" possibility exists where each record is length-prefixed: you wouldn't need to actually process everything, but you'd still need to read the header for each record, to skip through it.
Upvotes: 1