这是使一个流的输入的输出到另一个的最佳方式 [英] What is the best way to make the output of one stream the input to another
问题描述
我不知道是否有更好的/内置的方式,比用一个字节的缓冲区和循环,从一个流中读取和写入到另一个(在.NET)等。通常这样做是为了应用转换到流并将其移动
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;
编辑:
.NET 4.0现在有一个Stream.CopyTo功能,哈利路亚
.NET 4.0 now has a Stream.CopyTo function, Hallelujah
推荐答案
这里没有一个真正的比这更好的办法,但我更倾向于把循环部分成 CopyTo从
扩展方法,如:
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);
这篇关于这是使一个流的输入的输出到另一个的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!