【发布时间】: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