Stream.CopyTo() extension method
Join the DZone community and get the full member experience.Join For Free
In one of my applications I needed copy data from one stream to another. After playing with streams a little bit I wrote CopyTo() extension method to Stream class you can use to copy the contents of current stream to target stream. Here is my extension method.
It is my working draft and it is possible that there must be some more checks before we can say this extension method is ready to be part of some API or class library.
public static void CopyTo(this Stream fromStream, Stream toStream)
if (fromStream == null)
throw new ArgumentNullException("fromStream");
if (toStream == null)
throw new ArgumentNullException("toStream");
var bytes = new byte;
while ((dataRead = fromStream.Read(bytes, 0, bytes.Length)) > 0)
toStream.Write(bytes, 0, dataRead);
And here is example how to use this extension method.
using(var stream = response.GetResponseStream())I am using this code to copy data from HTTP response stream to memory stream because I have to use serializer that needs more than response stream is able to offer.
using(var ms = new MemoryStream())
// Do something with copied data
Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.