tags:

views:

208

answers:

3

I'm wondering if there is a better/inbuilt way, other than using a byte buffer and looping, to read from one stream and write it to another (in .NET). Generally this is done to apply a transform to a stream and move it on.

In this instance, what I am loading a file, putting it through a deflate stream and writing it out to a file (Error handling removed for simplicity):

byte[] buffer = new byte[10000000];
using (FileStream fsin = new FileStream(filename, FileMode.Open))
{
    using (FileStream fsout = new FileStream(zipfilename, FileMode.CreateNew))
    {
        using (DeflateStream ds = new DeflateStream(fsout, CompressionMode.Compress))
        {
            int read = 0;
            do
            {
                read = fsin.Read(buffer, 0, buffer.Length);
                ds.Write(buffer, 0, read);
            }
            while (read > 0);
        }
    }
}
buffer = null;

Edit:

.NET 4.0 now has a Stream.CopyTo function, Hallelujah

+1  A: 

Now that I think about it, I haven't ever seen any built-in support for piping the results of an input stream directly into an output stream as you're describing. This article on MSDN has some code for a "StreamPipeline" class that does the sort of thing you're describing.

Matt Hamilton
+5  A: 

There's not really a better way than that, though I tend to put the looping part into a CopyTo extension method, e.g.

public static void CopyTo(this Stream source, Stream destination)
{
    var buffer = new byte[0x1000];
    int bytesInBuffer;
    while ((bytesInBuffer = source.Read(buffer, 0, buffer.Length)) > 0)
    {
        destination.Write(buffer, 0, bytesInBuffer);
    }
}

Which you could then call as:

fsin.CopyTo(ds);
Greg Beech
Yes, I would do this if we were on 3.5. Generally we put it in a static method library.
Robert Wagner
Indeed, it used to be called StreamCopier.Copy before 3.5 :-)
Greg Beech
Note that it's fine if you're using .NET 2.0, so long as you're using C# 3. You can still use extension methods with a little bit of trickery. See http://csharpindepth.com/Articles/Chapter1/Versions.aspx
Jon Skeet
+1  A: 

.NET 4.0 now has a Stream.CopyTo function

Robert Wagner