【问题标题】:VB.NET Read Binary File into array of structuresVB.NET 将二进制文件读入结构数组
【发布时间】:2014-09-01 13:49:15
【问题描述】:

我尝试过使用 BinaryReader,但这绝对行不通。在第一个 reader.Readx 位时,它几乎塞满了。

所以,我改变了策略并尝试使用 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 传递。

什么可能导致这个错误?

昨晚我在想,每次读取记录时是否必须关闭并重新打开文件?

【问题讨论】:

    标签: arrays vb.net structure binaryfiles


    【解决方案1】:

    按使方法轻松工作的可能性降序排列:

    选项 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->比较。

    【讨论】:

    • 重新 PS,是的,我知道,这是我正在转换的其他人的代码(和拼写),他们有阅读障碍并且拼写有严重问题,让寻找单词的生活变得很难说至少!感谢您的提示,我会仔细阅读文档并试一试...
    猜你喜欢
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 2011-05-14
    相关资源
    最近更新 更多