2

I have got a binary file. I have no clue how to read this binary file using C#.

The definition of the records in the binary file as described in C++ is:

#define SIZEOF_FILE(10*1024)
//Size of 1234.dat file is: 10480 + 32 byte (32 = size of file header)
typedef struct FileRecord
{
 WCHAR ID[56]; 
 WCHAR Name[56];
 int Gender;
 float Height;
 WCHAR Telephne[56];
 and........
}

How do I read a binary file containing those records in C# and write it back after editing it?

Robert Gowland
  • 7,677
  • 6
  • 40
  • 58
User13839404
  • 1,803
  • 12
  • 37
  • 46

3 Answers3

5

There's actually a nicer way of doing this using a struct type and StructLayout which directly maps to the structure of the data in the binary file (I haven't tested the actual mappings, but it's a matter of looking it up and checking what you get back from reading the file):

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
public struct FileRecord
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 56)]
    public char[] ID;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 56)]
    public char[] Name;
    public int Gender;
    public float height;
    //...
}

class Program
{
    protected static T ReadStruct<T>(Stream stream)
    {
        byte[] buffer = new byte[Marshal.SizeOf(typeof(T))];
        stream.Read(buffer, 0, Marshal.SizeOf(typeof(T)));
        GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
        T typedStruct = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
        handle.Free();
        return typedStruct;
    }

    static void Main(string[] args)
    {
        using (Stream stream = new FileStream(@"test.bin", FileMode.Open, FileAccess.Read))
        {
            FileRecord fileRecord = ReadStruct<FileRecord>(stream);
        }
    }
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
  • +1 "...checking what you get back from reading the file" How would you do that, i.e. what are you looking for? I'm a complete newbie at working with binary data. – Adrian K Aug 10 '15 at 00:13
  • you have to know the layout of the binary data in your file, i.e. what is the record size, what are the fields in each record and what is their size. – BrokenGlass Aug 10 '15 at 02:42
4

See the sample below.

 public byte[] ReadByteArrayFromFile(string fileName)
{
  byte[] buff = null;
  FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
  BinaryReader br = new BinaryReader(fs);
  long numBytes = new FileInfo(fileName).Length;
  buff = br.ReadBytes((int)numBytes);
  return buff;
}

Hope that helps...

Kenn
  • 2,709
  • 2
  • 29
  • 60
0

You can use FileStream to read a file - use File.Open method to open a file and get a FileStream - look here for more details

Rafal Spacjer
  • 4,838
  • 2
  • 26
  • 34