Home:ALL Converter>How to read a binary file using c#?

How to read a binary file using c#?

Ask Time:2011-03-29T02:36:57         Author:User13839404

Json Formatter

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?

Author:User13839404,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/5463476/how-to-read-a-binary-file-using-c
BrokenGlass :

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):\n\n[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]\npublic struct FileRecord\n{\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = 56)]\n public char[] ID;\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = 56)]\n public char[] Name;\n public int Gender;\n public float height;\n //...\n}\n\nclass Program\n{\n protected static T ReadStruct<T>(Stream stream)\n {\n byte[] buffer = new byte[Marshal.SizeOf(typeof(T))];\n stream.Read(buffer, 0, Marshal.SizeOf(typeof(T)));\n GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);\n T typedStruct = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));\n handle.Free();\n return typedStruct;\n }\n\n static void Main(string[] args)\n {\n using (Stream stream = new FileStream(@\"test.bin\", FileMode.Open, FileAccess.Read))\n {\n FileRecord fileRecord = ReadStruct<FileRecord>(stream);\n }\n }\n",
2011-03-28T21:29:50
Kenn :

See the sample below. \n\n public byte[] ReadByteArrayFromFile(string fileName)\n{\n byte[] buff = null;\n FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);\n BinaryReader br = new BinaryReader(fs);\n long numBytes = new FileInfo(fileName).Length;\n buff = br.ReadBytes((int)numBytes);\n return buff;\n}\n\n\nHope that helps... ",
2011-03-28T19:04:21
yy