我試過使用BinaryReader,但那絕對不行。它在第一個閱讀器上幾乎是塞滿了.Readx位。VB.NET讀取二進制文件到結構數組
所以,我已經改變了方向,並試圖使用FILEOPEN,FILEGETOBJECT,FILEPUTOBJECT。
這是工作爲先「記錄」,但從此之後,我越來越
「嘗試讀取或寫入受保護的內存。這通常是指示其他內存已損壞」
這裏是到目前爲止的代碼:
Dim iFreeFile As Integer = FreeFile()
Dim iFileLength As Integer
' open the file
iFreeFile = FreeFile()
FileOpen(iFreeFile, inFilePath, OpenMode.Binary, OpenAccess.Read, OpenShare.Default)
iFileLength = FileLen(inFilePath)
' This bit reads the data
Dim recordLength As Integer = Marshal.SizeOf(outValue)
Dim myBytes As Byte() : ReDim myBytes(recordLength)
FileGet(iFreeFile, myBytes, inRecordCount)
BuildStr(myBytes, outValue.GetType, outValue)
inRecordCount += 1
outValue是幾種結構的一個
''' <summary>
''' ' Marshal the Byte Array to the Structure
''' </summary>
''' <param name="Buff">Array of Bytes</param>
''' <param name="MyType">Type of the Structure</param>
''' <param name="outBuffer">Structure Object</param>
Private Sub BuildStr(ByVal Buff() As Byte,
ByVal MyType As System.Type,
ByRef outBuffer As Object)
' Marshal the Byte Array to the Structure
Dim MyGC As GCHandle = GCHandle.Alloc(Buff, GCHandleType.Pinned)
'Marshals data from an unmanaged block of memory
'to a newly allocated managed object of the specified type.
outBuffer = Marshal.PtrToStructure(MyGC.AddrOfPinnedObject, MyType) ' <----- here we get the error
End Sub
myBytes數組從FileGet指令加載得很好。 outValue被傳遞給ByRef。
什麼可能導致此錯誤?
昨晚我有一個想法,每次讀取記錄時是否必須關閉並重新打開文件?
重新回到PS,是的,我知道,這是別人的代碼(和拼寫),我正在轉換,它們沒有反應,並且拼寫有嚴重問題,使得生活中搜索文字很難說! 感謝您的提示,我會仔細閱讀相關文檔,然後去... – JA12 2014-09-02 08:07:09