Question

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

Was it helpful?

Solution

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);

OTHER TIPS

.NET 4.0 now has a Stream.CopyTo function

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top