Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to make the output of one stream the input to another

Tags:

.net

iostream

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

like image 872
Robert Wagner Avatar asked Nov 25 '08 00:11

Robert Wagner


3 Answers

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);
like image 59
Greg Beech Avatar answered Oct 22 '22 23:10

Greg Beech


.NET 4.0 now has a Stream.CopyTo function

like image 31
Robert Wagner Avatar answered Oct 22 '22 23:10

Robert Wagner


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.

like image 33
Matt Hamilton Avatar answered Oct 22 '22 22:10

Matt Hamilton