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

大城市里の小女人 提交于 2019-12-07 04:42:29

问题


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:


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



回答2:


.NET 4.0 now has a Stream.CopyTo function




回答3:


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.



来源:https://stackoverflow.com/questions/316007/what-is-the-best-way-to-make-the-output-of-one-stream-the-input-to-another

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!