Search code examples
vb.nethexbyte

Reading only x number of bytes from file in VB.NET


I use this code to read full hex of file :

Dim bytes As Byte() = IO.File.ReadAllBytes(OpenFileDialog1.FileName)
Dim hex As String() = Array.ConvertAll(bytes, Function(b) b.ToString("X2"))

Can i only read like first X number of bytes and convert it to hex?

Thanks,


Solution

  • 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.