我使用此代码读取文件的完整十六进制:
Dim bytes As Byte() = IO.File.ReadAllBytes(OpenFileDialog1.FileName)
Dim hex As String() = Array.ConvertAll(bytes, Function(b) b.ToString("X2"))
我只能读取前 X 个字节并将其转换为十六进制吗?
谢谢,
There are a ton of ways of getting bytes from a file in .NET. One way is:
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
The arraySizeMinusOne
is the max index of your array - so setting to 5 means you'll get 6 bytes (indices 0 through 5).
This is a popular way of reading through a large file, one chunk at a time. Usually you'll set your buffer at a reasonable size, like 1024 or 4096, then read that many bytes, do something with them (like writing to a different stream), then move on to the next bytes. It's similar to what you would do with StreamReader
when dealing with a text file.