Skip to content

Instantly share code, notes, and snippets.

@jmcd
Created October 12, 2011 10:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmcd/1280878 to your computer and use it in GitHub Desktop.
Save jmcd/1280878 to your computer and use it in GitHub Desktop.
An extension method to read to the end of a stream
using System;
using System.IO;
namespace jmcd
{
public static class StreamExtensions
{
public static byte[] ReadToEnd(this Stream stream)
{
var result = new byte[0];
var buffer = new byte[4096];
int numberOfBytesRead;
while ((numberOfBytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
var oldLength = result.Length;
result = IncreaseCapacity(result, numberOfBytesRead);
Array.Copy(buffer, 0, result, oldLength, numberOfBytesRead);
}
stream.Close();
return result;
}
private static byte[] IncreaseCapacity(byte[] buffer, int numberOfBytesToIncrease)
{
var result = new byte[buffer.Length + numberOfBytesToIncrease];
Array.Copy(buffer, result, buffer.Length);
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment