在VB.NET中只能从文件中读取x个字节 [英] Reading only x number of bytes from file in VB.NET

查看:283
本文介绍了在VB.NET中只能从文件中读取x个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我可以只读取前X字节数并将其转换为十六进制吗?



谢谢,

解决方案

有很多方法可以从.NET中的文件获取字节。一种方法是:

pre $ Dim arraySizeMinusOne = 5
Dim buffer()As Byte = New Byte(arraySizeMinusOne){}
使用fs作为新的FileStream(fileName,FileMode.Open,FileAccess.Read,FileShare.None)
fs.Read(buffer,0,buffer.Length)
结束使用

arraySizeMinusOne 是数组的最大索引 - 所以设置到5意味着你将得到6个字节(索引0到5)。



这是一种阅读一个大文件的流行方式,一次一个大块。通常你会将缓冲区设置为一个合理的大小,比如1024或4096,然后读取那么多字节,用它们做一些事情(比如写入不同的流),然后继续下一个字节。这与处理文本文件时使用 StreamReader 所做的相似。


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,

解决方案

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.

这篇关于在VB.NET中只能从文件中读取x个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆