0

I have a BinaryReader/BinaryWriter with a length of 1000 bytes, each record is 50 bytes. How can I eliminate the records at position 350 to 550 and in the end keep the remaining 800 bytes in my file?

Martin Liversage
  • 104,481
  • 22
  • 209
  • 256
fma3
  • 571
  • 2
  • 5
  • 10
  • Easiest would probably be to just read and save the first 7 records, read 4 more that you throw away and finally read and save the rest...? – Joachim Isaksson Feb 21 '12 at 17:57

2 Answers2

2

The simplest way would be to loop through the records, reading from one file and writing to a new one, and eliminating the records you don't need.

In theory you could seek within the same file, overwriting the "old" data with new data, but I'd personally go for a simple approach where possible. It also means that if anything fails half way through, you've still got the original file and a "bad" file which can just be deleted, rather than a file which may contain some records twice.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

You have to read the data from position 550 to the end of the file, and write that at position 350.

If you use a FileStream you could do that exact operation. Using a BinaryReader and BinaryWriter you would have to read all the data in the file and write back the data that you want to keep. For such a small file you can keep all the data in memory, but for a larger file you would write to a temporary file and let that replace the original file when you are done.

Writing to a temporary file may also be a good idea to minimise the risk of losing data. If something went wrong at any point in the operation you would have at least one intact file left on the disk.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005