2014-09-01 81 views
1

我試過使用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。

什麼可能導致此錯誤?

昨晚我有一個想法,每次讀取記錄時是否必須關閉並重新打開文件?

回答

0

在下降的可能性有多大,以獲得方法很容易地工作:

選項1在VB6在一個更加普遍的格式寫入數據寫一個小程序,XML說。這在VB.NET中閱讀起來會比較困難。

選項2在VB.NET中使用FileGet Function。絕對讀取該文檔中的所有備註,並參考VB6代碼如何首先寫入數據。如果事實證明FileGet不能與Option Strict On(我假定你正在使用)一起工作,那麼將讀取該文件的類放在一個單獨的類文件中,以便可以爲該類使用Option Strict Off。

選項3一次讀取文件到字節數組中並解析該文件。 How Visual Basic 6 Stores Data可能是有用的如果 VB6將數據存儲到磁盤的方式與將其存儲在RAM中的方式相同。


此外,你應該組織你的文件流和讀寫器用法如下,以確保一切佈置的整齊:

Using oFS As New FileStream(filePath, FileMode.Open, FileAccess.Read) 
    Using oBR As New BinaryReader(oFS) 

    ' reading code goes here 

    End Using 
End Using 

附: Comparitave->比較。

+0

重新回到PS,是的,我知道,這是別人的代碼(和拼寫),我正在轉換,它們沒有反應,並且拼寫有嚴重問題,使得生活中搜索文字很難說! 感謝您的提示,我會仔細閱讀相關文檔,然後去... – JA12 2014-09-02 08:07:09