Created
October 12, 2011 10:37
-
-
Save jmcd/1280878 to your computer and use it in GitHub Desktop.
An extension method to read to the end of a stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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