从FileStream获取字节数组的正确方法是什么?

时间:2011-06-17 09:10:59

标签: c# .net

Microsoft网站有代码段:

  using (FileStream fsSource = new FileStream(pathSource,
        FileMode.Open, FileAccess.Read))
    {
        // Read the source file into a byte array.
        byte[] bytes = new byte[fsSource.Length];
        int numBytesToRead = (int)fsSource.Length;
        int numBytesRead = 0;
        while (numBytesToRead > 0)
        {
            // Read may return anything from 0 to numBytesToRead.
            int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);

            // Break when the end of the file is reached.
            if (n == 0)
                break;

            numBytesRead += n;
            numBytesToRead -= n;
        }
    }

我担心的是fsSource.Lengthlong,而numBytesReadint,所以最多2 * int.MaxValue只能读入bytes FileStream (流的头部和尾部)。所以我的问题是:

  1. 有什么理由可以吗?
  2. 如果没有,您应该如何将byte[]读入{{1}}。

3 个答案:

答案 0 :(得分:3)

在这种情况下,我甚至不打算手动处理FileStream;改为使用File.ReadAllBytes

byte[] bytes = File.ReadAllBytes(pathSource);

答案 1 :(得分:3)

回答你的问题:

  1. 示例代码适用于我们未达到极端的大多数应用程序。
  2. 如果你有很长的流,就像说视频一样,请使用BufferedStream。示例代码可在MSDN网站上找到

答案 2 :(得分:-1)

使用ReadAllBytes的示例:

private byte[] m_cfgBuffer;
m_cfgBuffer = File.ReadAllBytes(m_FileName);
StringBuilder PartNbr = new StringBuilder();
StringBuilder Version = new StringBuilder();
int i, j;
byte b;
i = 356;    // We know that the cfg file header ends at position 356 (1st hex(80))
b = m_cfgBuffer[i];
while (b != 0x80)   // Scan for 2nd hex(80)
{
    i++;
    b = m_cfgBuffer[i];
}

// Now extract the part number - 6 bytes after hex(80)

m_PartNbrPos = i + 5;
for (j = m_PartNbrPos; j < m_PartNbrPos + 6; j++)
{
   char cP = (char)m_cfgBuffer[j];
   PartNbr.Append(cP);
}
m_PartNbr = PartNbr.ToString();

// Now, extract version number - 6 bytes after part number

m_VersionPos = (m_PartNbrPos + 6) + 6;
for (j = m_VersionPos; j < m_VersionPos + 2; j++)
{
   char cP = (char)m_cfgBuffer[j];
   Version.Append(cP);
}
m_Version = Version.ToString();