繁体   English   中英

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

[英]What is the correct way to get a byte array from a FileStream?

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 (流的开头和2 * int.MaxValue )。 所以我的问题是:

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

在这种情况下,我什至都不会手动处理FileStream 使用File.ReadAllBytes代替:

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

要回答您的问题:

  1. 该示例代码对于我们没有达到极限的大多数应用程序很有用。
  2. 如果您的视频流很长,例如说视频,请使用BufferedStream MSDN网站上提供了示例代码

使用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();

暂无
暂无

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

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