Reducing your lines of code is pretty simple here (while still working with arbitrary streams, rather than just files):
using (Stream fileStream = File.OpenRead(fileName))
using (MemoryStream memoryStream = new MemoryStream())
{
int byteRead;
while ((byteRead = fileStream.ReadByte()) != -1)
{
memoryStream.WriteByte(byteRead);
}
return memoryStream.ToArray();
}
Obviously it's a lot more efficient to read into a buffer than to read a byte at a time, but this reduces the number of statements (as you don't need to declare both a buffer and a variable to hold the return value from Stream). Calling MemoryStream.ToArray()
is simpler than reading into a newly constructed array.
Using a buffer is nicer though. Note that we really don't need BinaryReader:
using (Stream fileStream = File.OpenRead(fileName))
using (MemoryStream memoryStream = new MemoryStream())
{
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
memoryStream.Write(buffer, 0, bytesRead);
}
return memoryStream.ToArray();
}
If you want to be really brutal, we could reduce the number of using
statements (with either solution):
using (Stream fileStream = File.OpenRead(fileName),
memoryStream = new MemoryStream())
{
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
memoryStream.Write(buffer, 0, bytesRead);
}
return ((MemoryStream)memoryStream).ToArray();
}
But that's just nasty :)
Another option of course is to use a library such as MiscUtil which has a method to read fully from a stream :) The utility method can be as simple as this:
public static byte[] ReadFully(this Stream stream)
{
using (MemoryStream memoryStream = new MemoryStream())
{
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
memoryStream.Write(buffer, 0, bytesRead);
}
return memoryStream.ToArray();
}
}
Note that this never closes the stream - the caller should do that.