hitesh jain
hitesh jain

Reputation: 119

How can I read a binary file without knowing the datatype of the next value?

I want to read my binary file which has char, String, and Integers in it . How should I read it? I have tried to read my file my the below function and it works fine, but how can I read the file without knowing the data type of the next value?

static void read() // Read Function 
{
    FileStream a = new FileStream("bin.txt", FileMode.Open);
    BinaryReader b = new BinaryReader(a);

    int pos = 0;
    Console.WriteLine(b.ReadChar());
    Console.WriteLine(b.ReadChar());
    Console.WriteLine(b.ReadString());
    Console.WriteLine(b.ReadInt32());
}

static void write() // Write Function This What My File consist Of Data. 
{
    BinaryWriter al = new BinaryWriter(File.Create("bin.txt"));
    char a = 'l';
    al.Write(a);
    a = 'p';
    al.Write(a);
    string l = "loremm";
    al.Write(l);
    al.Write(1233);
    al.Close();
}

Upvotes: 3

Views: 346

Answers (1)

mksteve
mksteve

Reputation: 13073

Successful binary file types have rules for the order of data.

These can be structure based. E.g. an archive format may precede file data with

struct {
    char name[256];
    size_t uncompressedSize;
    size_t compressedsize;
    short  compressionmethod;
};

or C#

using System.Runtime.InteropServices;


[StructLayout(LayoutKind.Explicit, Size = 276, Pack = 1)]
public struct NewStuff
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
    [FieldOffset(0)]
    public string Name;

    [MarshalAs(UnmanagedType.U8)]
    [FieldOffset(256)]
    public UInt64 uncompressedSize;

    [MarshalAs(UnmanagedType.U8)]
    [FieldOffset(264)]
    public UInt64 compressedSize;


    [MarshalAs(UnmanagedType.U2)]
    [FieldOffset(272)]
    public UInt16 compressionMethod;
}

This allows chunks of data to be read, and the type of following data to be known afterwards.

Alternatively, you could 'tag' the data e.g.

Inttag; intvalue ; stringtag ; string value

This can include 'named' items e.g. 'file data' which then names the next record.

Upvotes: 2

Related Questions