【问题标题】:How to Load Binary File Into Struct and get the data?如何将二进制文件加载到结构中并获取数据?
【发布时间】:2015-10-30 21:44:08
【问题描述】:

我已在 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:\dat\bintest.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 什么都没有显示,就像没有读取文件一样

有什么解决办法吗? 谢谢!

【问题讨论】:

    标签: c# struct stream binaryreader


    【解决方案1】:

    改变

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

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

    【讨论】:

    • 我在评论之前已经使用它,但结果似乎相同
    • 但是我可以使用 ByValTStr 运行代码,而使用 LPStr 时总是遇到访问冲突错误。 ByValTStr 会将 156 个字节加载到您的结构中,这是肯定的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多