简体   繁体   English

从VB.NET中的文件仅读取x个字节

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

I use this code to read full hex of file : 我使用此代码读取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? 我可以只读取前X个字节并将其转换为十六进制吗?

Thanks, 谢谢,

There are a ton of ways of getting bytes from a file in .NET. 有很多方法可以从.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). arraySizeMinusOne是数组的最大索引-因此设置为5意味着您将获得6个字节(索引从0到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. 通常,您将缓冲区设置为合理的大小,例如1024或4096,然后读取那么多字节,对它们进行某些操作(例如写入不同的流),然后继续下一个字节。 It's similar to what you would do with StreamReader when dealing with a text file. 这类似于处理文本文件时对StreamReader进行的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM