我正在嘗試使用C#讀取二進制數據。我擁有關於我想要讀取的文件中數據佈局的所有信息。我能夠讀取數據「塊大塊」,即獲得前40個字節的數據將其轉換爲字符串,獲得接下來的40個字節。將二進制文件讀入結構中
由於至少有三個稍微不同的版本的數據,我想直接讀取數據到一個結構。它只是比「逐行閱讀」更讓人感覺正確。
我曾嘗試以下方法,但都無濟於事:
StructType aStruct;
int count = Marshal.SizeOf(typeof(StructType));
byte[] readBuffer = new byte[count];
BinaryReader reader = new BinaryReader(stream);
readBuffer = reader.ReadBytes(count);
GCHandle handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned);
aStruct = (StructType) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(StructType));
handle.Free();
流是打開的FileStream從中我已經開始從閱讀。當使用Marshal.PtrToStructure
時,我得到一個AccessViolationExceptio
n。
流包含的信息比我想要讀取的更多,因爲我對文件末尾的數據不感興趣。
的結構的定義如下:
[StructLayout(LayoutKind.Explicit)]
struct StructType
{
[FieldOffset(0)]
public string FileDate;
[FieldOffset(8)]
public string FileTime;
[FieldOffset(16)]
public int Id1;
[FieldOffset(20)]
public string Id2;
}
的示例代碼是從原始改變,使這一問題更短。
如何將二進制數據從文件讀取到結構中?
BinaryFormatter有自己的二進制數據格式 - 如果您自己讀取/寫入數據,這很好。如果您從其他來源獲取文件則無用。 – russau 2009-07-26 07:11:52