Visual Basic读取Binary/Hex二进制文件输出空/Null值问题求助
问题根因
BinaryReader.ReadString()方法仅支持读取由.NET BinaryWriter写入的带7位整数长度前缀的字符串,直接读取自定义二进制文件中的原生字符串时,会将字符串首字节错误识别为长度值,首字节为0时就会返回空值。- 原有循环逻辑无效:每次调用
ReadString()会自动移动流的位置指针,你设置的按字节位置遍历的循环不会按预期执行。
修复方案
首先确认二进制文件中字符串的存储规则:是\0结尾的C风格字符串、固定长度字符串,以及对应的编码(ASCII/UTF-8/Unicode/GB2312等),以下提供两种常见场景的实现:
场景1:字符串为\0结尾的ASCII字符串(最常见的游戏/工具二进制资源存储格式)
Imports System.IO Imports System.Text Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Dim path As String = "C:\Users\USER\PATH\TO\file.bin" Const START_OFFSET As Long = 502004 Const END_OFFSET As Long = 502173 Dim itemNameList As New List(Of String) ' 后续可直接绑定到ListView控件 Using fs As FileStream = File.Open(path, FileMode.Open), reader As New BinaryReader(fs) reader.BaseStream.Position = START_OFFSET ' 逐字符串读取直到达到结束偏移 While reader.BaseStream.Position < END_OFFSET Dim byteCache As New List(Of Byte) Dim curByte As Byte = reader.ReadByte() ' 读到\0或到达边界则停止当前字符串解析 While curByte <> 0 AndAlso reader.BaseStream.Position <= END_OFFSET byteCache.Add(curByte) curByte = reader.ReadByte() End While ' 按实际编码转换,中文可替换为Encoding.GetEncoding("GB2312")、Encoding.UTF8等 Dim itemName = Encoding.ASCII.GetString(byteCache.ToArray()).Trim() If Not String.IsNullOrEmpty(itemName) Then Console.WriteLine(itemName) itemNameList.Add(itemName) End If End While End Using ' 绑定到ListView示例 ' For Each name In itemNameList ' ListView1.Items.Add(name) ' Next Console.WriteLine("End") End Sub
场景2:字符串为固定长度存储
如果每个物品名占用固定字节数(比如每个占16字节),直接按固定长度读取即可:
' 替换上面的While循环内部逻辑即可 Const NAME_BYTE_LENGTH As Integer = 16 ' 替换为实际单条字符串的字节长度 While reader.BaseStream.Position + NAME_BYTE_LENGTH <= END_OFFSET Dim nameBytes = reader.ReadBytes(NAME_BYTE_LENGTH) Dim itemName = Encoding.ASCII.GetString(nameBytes).Trim(ChrW(0), " "c) If Not String.IsNullOrEmpty(itemName) Then Console.WriteLine(itemName) itemNameList.Add(itemName) End If End While
内容的提问来源于stack exchange,提问作者Groggy
相关产品推荐
相关产品推荐

