How to read a binary file using c#?

后端 未结 3 843
予麋鹿
予麋鹿 2021-01-03 12:43

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:



        
3条回答
  •  清酒与你
    2021-01-03 13:13

    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(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(stream);
            }
        }
    

提交回复
热议问题