我使用此代码来读取文件的完整十六进制:
Dim bytes As Byte() = IO.File.ReadAllBytes(OpenFileDialog1.FileName)
Dim hex As String() = Array.ConvertAll(bytes, Function(b) b.ToString("X2"))
我可以只读取前 X 个字节并将其转换为十六进制吗?
谢谢,
有很多方法可以从 .NET 中的文件中获取字节。一种方法是:
Dim arraySizeMinusOne = 5
Dim buffer() As Byte = New Byte(arraySizeMinusOne) {}
Using fs As New FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None)
fs.Read(buffer, 0, buffer.Length)
End Using
arraySizeMinusOne
是数组的最大索引 - 因此设置为 5 意味着您将获得 6 个字节(索引 0 到 5)。
这是一种一次读取大文件的流行方式。通常,您会将缓冲区设置为合理的大小,例如 1024 或 4096,然后读取那么多字节,对它们执行某些操作(例如写入不同的流),然后继续处理下一个字节。这与处理文本文件时使用
StreamReader
的操作类似。
在具有偏移支持的更高级情况下,我在开源 DLL 文件中找到了此代码。
Function readX(ByVal file As String, ByVal from As UInt64, ByVal count As UInt64) As Byte()
'hon Code 2023 (FUNCT v1.0.00)
Dim buffer() As Byte = New Byte(count) {}
Using fs As New FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read)
fs.Seek(2, SeekOrigin.Begin)
fs.Read(buffer, 0, count)
End Using
Return buffer
End Function
基本用法是
readX(file, offset, count)
例如
readX("test.txt", 2, 2)
它从 test.txt 文件的第 2 到第 4 个字节读取。