I'm trying to parse a crg-file in C#. The file is mixed with plain text and binary data. The first section of the file contains plain text while the rest of the file is binary (lots of floats), here's an example:
$
$ROAD_CRG
reference_line_start_u = 100
reference_line_end_u = 120
$
$KD_DEFINITION
#:KRBI
U:reference line u,m,730.000,0.010
D:reference line phi,rad
D:long section 1,m
D:long section 2,m
D:long section 3,m
...
$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
�@z����RA����\�l
...
I know I can read bytes starting at a specific offset but how do I find out which byte to start from? The last row before the binary section will always contain at least four dollar signs "$$$$". Here's what I've got so far:
using var fs = new FileStream(@"crg_sample.crg", FileMode.Open, FileAccess.Read);
var startByte = ??; // How to find out where to start?
using (BinaryReader reader = new BinaryReader(fs))
{
reader.BaseStream.Seek(startByte, SeekOrigin.Begin);
var f = reader.ReadSingle();
Debug.WriteLine(f);
}
StreamReaderwith theleaveOpenconstructor parameter set totrue. Then you can simply read lines until you've seen the separator line and start using theBinaryReader, as the stream will be positioned correctly. Alternatively, of course, you can use theBinaryReaderto hunt for four consecutive0x24bytes ($), then read to the next newline, then start reading floats (i.e. implement your own little state machine) but that's more complicated.StreamReaderto support this scenario anyway (given that we have a seekable stream). In the general case with buffered forward-only access you do have to get more complicated, of course.Span<byte>. Perhaps even map bytes to structs directly. Or you could useSystem.IO.Pipelinesfor an API that allows you to move back and forth in the file. You have to treat that files as binary though$$$$$lines. Is that separator well defined? If so, you can use one parser for everything up to it and a completely different one for the rest of the file.