Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using BinaryWriter to seek and insert data

Background:

I'm fairly new to C# and currently working on a project intended primarily for learning. I am creating a library to work with .PAK files, as used by Quake and Quake II. I can read and extract them fine, as well as writing a blank archive, and I'm on to writing data to the archive.

The basic specification can be found here for reference: http://debian.fmi.uni-sofia.bg/~sergei/cgsr/docs/pak.txt

Issue:

I would like to seek to the end of the binary data portion and insert data from a given file. I use BinaryWriter in the method when creating an empty file, so this is what I'm looking to use for insertion. From what I found, seeking and writing with BinaryWriter will write at a given position and overwrite existing data.

My goal is to simply insert data at a given point without losing any existing data. If this is not possible, I imagine that I will need to extract the entire index containing the individual file information (name, offset, length), add binary data, then append the index and append information for the file I am writing.

Any thoughts or suggestions?

like image 857
Edward Wymer Avatar asked Sep 17 '25 01:09

Edward Wymer


2 Answers

You can't insert data to a file directly using the C# IO classes. The easiest way would be to either read it into a buffer and manipulate the buffer, or write the first part to a temp file, then insert your new data, and then write the remainder of the file and then rename it. Alternatively you can append some data at the end of the file and move everything up to create the right amount of usable space where you want to insert your data.

Take a look at http://www.codeproject.com/Articles/17716/Insert-Text-into-Existing-Files-in-C-Without-Temp

like image 57
Martin Ernst Avatar answered Sep 19 '25 11:09

Martin Ernst


Using Stream-based objects (like FileStream) directly is better option for file level manipulations.

There is no way to insert data in the middle into any file, you have to either read whole file and save it back with newly inserted portions or copy to new file up to insertion point, add new data and than copy the rest (you can delete original/rename new at this point).

like image 33
Alexei Levenkov Avatar answered Sep 19 '25 09:09

Alexei Levenkov