Search code examples
c#binaryfilesdescriptorbinaryreader

C# BinaryReader - data which may or may not be in binary file


I am using binary file for storing measured data of some product. The product was the only one type before, now I have to be able to save/load more types of product.

I'm going to save some type descriptor at the beginning of the file, 1 Byte should be absolutely enough, there will be only a few types (2, maybe 3 or 4 in future).

The problem is, that I still need to be able load old binary files without this descriptor. Here is my old code with commentary where I want to check presence of descriptor and afterwards make a decision about product type like this:

  1. No descriptor -> old product
  2. Descriptor = xxx -> new product xxx

Is it possible to save descriptor in such a format? I guess the calling reader.PeekChar() is only one possibility because of not moving to next bytes, but I'm not sure how to use it in this case.

     BinaryReader reader;
     using (reader = new BinaryReader(File.Open(header.path, FileMode.Open, FileAccess.Read)))
     {
         // ...
         // check presence of product type descriptor
         // make a decision of type
         // ...

         DateTime measTime = DateTime.FromOADate(reader.ReadDouble());
         double diameter = reader.ReadDouble();
         double plusToler = reader.ReadDouble();
         double minusToler = reader.ReadDouble();
     }

Solution

  • The problem if I understand correclty is that you don't know whether you're reading the type descriptor (new file) or the first data value (old file).

    One simple way to solve this is to choose a different file extension for the new files - but depending on your situation this may not be an option.

    If not, you could prefix the product descriptor with a magic value which never (or unlikely) appears in the old file format. Something as simple as the ASCII characters "TYP" followed by the product descriptor byte would be quite unlikely to appear in the old file format (which starts with a double value).

    You could even choose to serialize double.MinValue as your magic value, as DateTime.FromOADate can only read

    a value between negative 657435.0 through positive 2958465.99999999

    That would completely rule out falsely identifying an old file as a new one.