如何从 vb.net 中的二进制文件中读取 vb6 固定长度字符串

问题描述

上下文

我有一个 vb6 软件使用这种特殊的类型

Type Example
    A As Integer
    B As Single
    C As String * 10
    D  As Byte
    E As String
End Type

这个结构完全保存在一个简单的“put”二进制文件中:

Dim Numfile%
Numfile = FreeFile
[...]
Put #Numfile,example_instance
[...]

问题

现在我想从 vb.net (.NET Framework 4) 读取这个二进制文件。问题是在 .net 中我们没有固定的字符串......我试图写一些类似的东西:

Structure Example
     Dim A As Short
     Dim B As Single 
     Dim C() As Char ' ---> This should replace String * 10.
     Dim D As Byte 
     Dim E As String 
End Structure

然后我读取文件

Dim n as short = FreeFile()
Dim instance as Example
If FileExists(filename) Then
    FileOpen(n,filename,OpenMode.Binary,OpenAccess.Read)
    [...]        
    FileGet(n,instance)
    [...]

但是,很明显,原始数据没有被正确检测到。

如何在 vb.net 中正确读取这个二进制文件

解决方法

我会写这个作为答案,即使我不是 100% 确定它会起作用,因为它不是我做过的事情。 VBFixedString 属性专门用于 VB6 使用固定长度 String 的情况。因此,我认为像这样声明你的类型:

Structure Example
     Dim A As Short
     Dim B As Single
     <VBFixedString(10)> Dim C As String
     Dim D As Byte
     Dim E As String
End Structure

应该可以解决问题。