1: /// <summary>
2: /// Reads the contents of the stream into a byte array.
3: /// data is returned as a byte array. An IOException is
4: /// thrown if any of the underlying IO calls fail.
5: /// </summary>
6: /// <param name="stream">The stream to read.</param>
7: /// <returns>A byte array containing the contents of the stream.</returns>
8: /// <exception cref="NotSupportedException">The stream does not support reading.</exception>
9: /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed.</exception>
10: /// <exception cref="System.IO.IOException">An I/O error occurs.</exception>
11: public static byte[] ReadAllBytes(this Stream source)
12: {
13: long originalPosition = source.Position;
14: source.Position = 0;
15:
16: try
17: {
18: byte[] readBuffer = new byte[4096];
19:
20: int totalBytesRead = 0;
21: int bytesRead;
22:
23: while ((bytesRead = source.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
24: {
25: totalBytesRead += bytesRead;
26:
27: if (totalBytesRead == readBuffer.Length)
28: {
29: int nextByte = source.ReadByte();
30: if (nextByte != -1)
31: {
32: byte[] temp = new byte[readBuffer.Length * 2];
33: Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
34: Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
35: readBuffer = temp;
36: totalBytesRead++;
37: }
38: }
39: }
40:
41: byte[] buffer = readBuffer;
42: if (readBuffer.Length != totalBytesRead)
43: {
44: buffer = new byte[totalBytesRead];
45: Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
46: }
47: return buffer;
48: }
49: finally
50: {
51: source.Position = originalPosition;
52: }
53: }