PumpStream
PumpStream is a handy C# static method for moving (or "pumping") all the bytes from one stream to another.
It's helpful when you want to move data from a FileStream into a DeflateStream, for example. Another
good use is streaming data from a MemoryStream or FileStream to a client via ASP.NET's Response.OutputStream
property.
Since PumpStream uses a configurable size intermediate buffer, you're never going to run out of memory no matter
how much data you're pumping.
Download
Code
1
2
3
4 using System;
5 using System.Collections;
6 using System.IO;
7
8 namespace JC.Utility {
9 public static class IOHelper {
10
11
12
13
14
15
16
17
18
19 public static int PumpStream(Stream input, Stream output) {
20 return PumpStream(input, output, 8192);
21 }
22
23
24
25
26
27
28
29
30
31
32
33 public static int PumpStream(Stream input, Stream output, int pumpBufferSize) {
34 if (input == null) {
35 throw new ArgumentNullException("input", "Input stream cannot be null.");
36 }
37
38 if (output == null) {
39 throw new ArgumentNullException("output", "Output stream cannot be null.");
40 }
41
42 if (pumpBufferSize < 1) {
43 throw new ArgumentOutOfRangeException("pumpBufferSize", pumpBufferSize, "PumpBufferSize cannot be less than 1 byte.");
44 }
45
46 byte[] bytes = new byte[pumpBufferSize];
47 int numBytesRead;
48 int totalBytesRead = 0;
49 try {
50 while ((numBytesRead = input.Read(bytes, 0, pumpBufferSize)) > 0) {
51 totalBytesRead += numBytesRead;
52 output.Write(bytes, 0, numBytesRead);
53 }
54 output.Flush();
55 } finally {
56 input.Close();
57 }
58
59 return totalBytesRead;
60 }
61 }
62 }