【问题标题】:C# FileStream.Read doesn't read last blockC# FileStream.Read 不读取最后一个块
【发布时间】:2018-04-25 03:01:45
【问题描述】:

我将二进制文件逐块读取为十六进制。

当我使用 FileStream.Read 和 File.ReadAllBytes 时是不同的

  1. 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");
    }
    
  2. 文件.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


【解决方案1】:

您很可能认为它没有读取最后一个块。假设您有长度为 102 的文件。循环的第一次迭代读取前 100 个字节,一切都很好。但是第二个(最后一个)会发生什么?您将两个字节读入 read_buff,长度为 100。现在该缓冲区包含最后一个块的 2 个字节和前一个(第一个)块的 98 个字节,因为Read 不会清除缓冲区。然后你继续:

 foreach (byte b in read_buff)
 {
    sb.Append(Convert.ToString(b, 16).PadLeft(2, '0'));
 }

结果,sb 有 100 个字节的第一个块,2 个字节的最后一个块,然后又是 98 个字节的第一个块。如果你不仔细看,它可能看起来只是跳过了最后一个块,而实际上它复制了前一个块的一部分。

要解决此问题,请使用count(指示真正读入缓冲区的字节数)仅使用read_buff 的有效部分:

for (int i = 0; i < count; i++) {
    sb.Append(Convert.ToString(read_buff[i], 16).PadLeft(2, '0'));
}

【讨论】:

    【解决方案2】:

    您需要更新偏移量和计数。

    辛特克斯

    public override int Read(
        byte[] array,
        int offset,
        int count
    )
    

    例子

    public static byte[] ReadFile(string filePath)
    {
      byte[] buffer;
      FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
      try
      {
        int length = (int)fileStream.Length;  // get file length
        buffer = new byte[length];            // create buffer
        int count;                            // actual number of bytes read
        int sum = 0;                          // total number of bytes read
    
        // read until Read method returns 0 (end of the stream has been reached)
        while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
          sum += count;  // sum is a buffer offset for next reading
      }
      finally
      {
        fileStream.Close();
      }
      return buffer;
    }
    

    Reference

    【讨论】:

    • 您应该使用using 而不是try-finally-Close。但更重要的是,如果您使缓冲区与文件大小相同(这对于非常大的文件来说是个坏主意),为什么不一次性读取所有内容呢?
    • 你应该查看官方文档msdn// Read may return anything from 0 to numBytesToRead. int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);
    【解决方案3】:
       public static void ReadAndProcessLargeFile(string theFilename, long whereToStartReading = 0)
        {
            FileInfo info = new FileInfo(theFilename);
            long fileLength = info.Length;
            long timesToRead = (fileLength / megabyte);
            long ctr = 0;
            long timesRead = 0;
    
            FileStream fileStram = new FileStream(theFilename, FileMode.Open, FileAccess.Read);
            using (fileStram)
            {
                byte[] buffer = new byte[megabyte];
    
                fileStram.Seek(whereToStartReading, SeekOrigin.Begin);
    
                int bytesRead = 0;
                
                //bytesRead = fileStram.Read(buffer, 0, megabyte);
                //ctr = ctr + 1;
    
                while ((bytesRead = fileStram.Read(buffer, 0, megabyte)) > 0)
                {
                    ProcessChunk(buffer, bytesRead);
                    buffer = new byte[megabyte]; // This solves last read prob
                }
    
            }
        }
    
        private static void ProcessChunk(byte[] buffer, int bytesRead)
        {
            // Do the processing here
            string utfString = Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.Write(utfString);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 2011-06-01
      • 1970-01-01
      • 2021-04-02
      • 2016-04-10
      相关资源
      最近更新 更多