【发布时间】:2018-04-25 03:01:45
【问题描述】:
我将二进制文件逐块读取为十六进制。
当我使用 FileStream.Read 和 File.ReadAllBytes 时是不同的
-
FileStram.Read
int limit = 0; if (openFileDlg.FileName.Length > 0) { fileName = openFileDlg.FileName; FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); fsLen = (int)fs.Length; int count = 0; limit = 100; byte[] read_buff = new byte[limit]; StringBuilder sb = new StringBuilder(); while ( (count = fs.Read(read_buff, 0, limit)) > 0) { foreach (byte b in read_buff) { sb.Append(Convert.ToString(b, 16).PadLeft(2, '0')); } } rtxb_bin.AppendText(sb.ToString() + "\n"); } -
文件.ReadAllBytes
if (openFileDlg.FileName.Length > 0) { fileName = openFileDlg.FileName; byte[] fileBytes = File.ReadAllBytes(fileName); StringBuilder sb2 = new StringBuilder(); foreach (byte b2 in fileBytes) { sb2.Append(Convert.ToString(b2, 16).PadLeft(2, '0')); } rtxb_allbin.AppendText(sb2.ToString()); }
案例1,结果是……
........04c0020f00452a00421346108129844f2138448500208020250405250043188510812e0
情况2是
.......04c0020f00452a00421346108129844f2138448500208020250405250043188510812e044f212cc48120c24125404f2069c2c0008bff35f8f401efbd17047
FileStream.Read 在 '12e0' 之后不读取 '44f212cc48120c24125404f2069c2c0008bff35f8f401efbd17047' 不见了
如何使用 FileStream.Read 读取所有字节?
为什么 FileStream.Read 不读取最后一个块?
【问题讨论】:
-
我认为这不是问题,但
foreach (byte b in read_buff)不适用于最后一个块。你应该阅读这个:for(var i = 0; i < count; i++). -
@Kown 如果您将
limit提高到该级别,以便一次读取整个流,您仍然面临同样的问题吗? -
提示:
b.ToString("x2")也会打印两个十六进制数字
标签: c# filestream