问题描述
我知道可以使用 sourceStream.CopyTo(targetStream);
将一个流复制到另一个流,但是我想将 sourceStream
的内容复制到中的两个目标流>两个不同的 Task
s .当我两次调用此方法时,第二次流为空.
I know it's possible to copy one stream to another with sourceStream.CopyTo(targetStream);
but I want to copy content of sourceStream
to two destination streams in two different Task
s. When I call this method two times, in second time stream is empty.
那有可能吗?一种简单的方法是将流内容加载到内存中,然后将其复制到目标上,但这可能会导致 OutOfMemoryException
.
Is that possible at all? A simple way is to load stream content to memory then copy it on targets, but it may cause OutOfMemoryException
.
如果有问题,我正在使用.Net 4.5
If it matters I'm using .Net 4.5
推荐答案
如果要同时将它复制到两个目标 ,则类似以下内容:
If you're copying it to two destinations at the same time, then something like:
byte[] buffer = new byte[SOME_SIZE];
int bytesRead;
while((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
{
dest1.Write(buffer, 0, bytesRead);
dest2.Write(buffer, 0, bytesRead);
}
这将遍历输入流一次,将每个块写入两个输出.这几乎是 CopyTo
内部执行的操作-唯一的区别是第二个输出.
This iterates through the input stream once, writing each chunk to two outputs. This is pretty much what CopyTo
does internally - the only difference is the second output.
这篇关于在两个目的地复制流内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!