satnhak
satnhak

Reputation: 9861

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

The Microsoft website has the code snippet:

  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;
        }
    }

What concerns me is that fsSource.Length is a long, whereas numBytesRead is an int so at most only 2 * int.MaxValue can be read into bytes (the head and the tail of the stream). So my questions are:

  1. Is there some reason that this is OK?
  2. If not, how should you read a FileStream into a byte[].

Upvotes: 1

Views: 658

Answers (3)

Jim Lahman
Jim Lahman

Reputation: 2757

Example using 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();

Upvotes: -1

sandyiit
sandyiit

Reputation: 1705

To answer your question:

  1. The sample code is good for most of applications where we are not reaching extremes.
  2. If you have really long stream like say a video, use BufferedStream. Sample code is available at MSDN site

Upvotes: 3

LukeH
LukeH

Reputation: 269278

In this situation I wouldn't even bother processing the FileStream manually; use File.ReadAllBytes instead:

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

Upvotes: 3

Related Questions