简体   繁体   中英

Parsing a binary file with multiple data types into an array

I've created multiple binary files, each containing 2 strings, 2 chars, 1 double, and 1 int. The data, when read, is

Fokker DR 1 
Germany 
D 
A 
1000.0 
13

And the binary file reads as follows: dat文件文字

I am trying to parse the dat file into an array so I can label each data type with the appropriate name such as

Name: Fokker DR 1
Country: Germany
Attack Mode: D
Turn Mode: A
etc.

But I am having trouble because, when trying to use StreamReader and split the binary file at every instance of a whitespace, I run into problems due to the fact that the Name (Fokker DR 1) contains multiple spaces that should not be split.

Here is my code for my attempted split:

if (file.Contains("plane1"))
{
    StreamReader reader = new StreamReader("plane1.dat");
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        string[] data = line.Split(' ');
        bin.ReadBinary("plane1.dat");
        Console.WriteLine("Name: " + data[0]);
        Console.WriteLine("Country: " + data[1]);
        Console.WriteLine("Turn Mode: " + data[2]);
        Console.WriteLine("Attack Mode: " + data[3]);
        Console.WriteLine("Cost: " + data[4]);
        Console.WriteLine("Max Damage: " + data[5]);
    }
}

Is there any sort of way to split at every instance of a different data type or is there another way to go about labeling the data in my binary file??

The BinaryFormatter will not handle that file format. Given the small size and straight forward specs some ustom read logic should do the trick.

If you open your file with a BinaryReader you can decide for your self what to do with the next byte or bytes you're about to read. If the format of the file is not to complex this is easy doable. Based on your specs I created this code to read your file:

using(var br = new BinaryReader(
    File.Open(@"c:\tmp\plane.dat", FileMode.Open),
    Encoding.ASCII))
{
    while(br.BaseStream.Position < br.BaseStream.Length)
    {
        var name = br.ReadString();
        var country = br.ReadString();
        var turnmode = br.ReadChar();
        var attackmode = br.ReadChar();
        var cost = br.ReadDouble();
        var maxdamage = br.ReadInt32();

        // you can use above vars what ever you need to do 
        // with them, writing to the console or adding to 
        // a list for example
        // Planes.Add(new Plane {Name = name});
    }
}

In my test a file I created matched your binary format. As you didn't show where the next record start you might find that you need to do an extra read, for example with a ReadByte but that depends on your actual structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM