Before you repeat this anti-pattern:
using (var stream = new FileStream("myFile.txt",FileMode.Open))
{
var bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
}
Make sure you’ve read the MSDN docs for Stream.Read :
Stream.Read Method
When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
Namespace: System.IO
Assembly: mscorlib (in mscorlib.dll)
public abstract int Read( byte[] buffer, int offset, int count )
Parameters
buffer
Type: System.Byte()
An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count – 1) replaced by the bytes read from the current source.
offset
Type: System.Int32
The zero-based byte offset in buffer at which to begin storing the data read from the current stream.
count
Type: System.Int32
The maximum number of bytes to be read from the current stream.
Return Value
Type: System.Int32
The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
Notice the wording for count? Maximum number of bytes to be read, and the return value is how many were actually read. There’s no guarantee that the stream will able in any fit state to serve your request for all the bytes in one go. The following, whilst longer, does ensure you read all the bytes from the stream, every time. Guess where the examples from? That’s right – the MSDN page:
Stream s = new MemoryStream();
for (int i = 0; i < 100; i++)
{
s.WriteByte((byte)i);
}
s.Position = 0;
// Now read s into a byte buffer.
byte[] bytes = new byte[s.Length];
int numBytesToRead = (int) s.Length;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
// Read may return anything from 0 to 10.
int n = s.Read(bytes, numBytesRead, 10);
// The end of the file is reached.
if (n == 0)
{
break;
}
numBytesRead += n;
numBytesToRead -= n;
}
s.Close();
// numBytesToRead should be 0 now, and numBytesRead should equal 100.
Console.WriteLine("number of bytes read: {0:d}", numBytesRead);
