如何将二进制文件加载到结构中并获取数据



我已经完成了在stackoverflow上搜索任何主题来解决我的问题,但我仍然无法用我的代码解决问题我想用c#读取二进制文件,并为其制作一个结构

这是代码

    [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Auto)]
    public struct YourStruct
    {            
        [FieldOffset(44)]
        public int none;  // 4 bytes
        [FieldOffset(48)]
        //[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 156)]
        [MarshalAs(UnmanagedType.LPTStr, SizeConst = 156)]
        public String alldata;
    }
    private void button1_Click(object sender, EventArgs e)
    {
        string strFilePath = @"F:datbintest.bin";
        FileStream stream = File.OpenRead(strFilePath);
        YourStruct aStruct;
        //int count = Marshal.SizeOf(typeof(YourStruct));
        int count = 791616;
        byte[] readBuffer = new byte[count];
        BinaryReader reader = new BinaryReader(stream);
        readBuffer = reader.ReadBytes(count);
        GCHandle handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned);
        aStruct = (YourStruct)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(YourStruct));
        handle.Free();
        Console.WriteLine("None = {0}", aStruct.none);
        Console.WriteLine("Data : {0}", aStruct.alldata);
    }

问题是,当我运行这个项目时,aStruct.alldata什么都没有显示,就像没有读取文件一样

有什么解决方案吗?谢谢

更改

[MarshalAs(UnmanagedType.LPTStr, SizeConst = 156)]

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 156)] 

最新更新