Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy stream content on two destinations

Tags:

c#

stream

copy

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 Tasks. When I call this method two times, in second time stream is empty.

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.

If it matters I'm using .Net 4.5

like image 573
vakarami Avatar asked Oct 20 '25 01:10

vakarami


1 Answers

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

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.

like image 195
Marc Gravell Avatar answered Oct 21 '25 15:10

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!