Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
DZone MVB

Links

Social

Stream.CopyTo() extension method

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[8092];

    int dataRead;

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

using(var ms = new MemoryStream())

{

    stream.CopyTo(ms);
 

    // Do something with copied data

}


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.

Posted: Dec 28 2010, 03:24 AM by DigiMortal | with 12 comment(s)
Filed under: ,

Comments

Ryan Anderson said:

A safety measure may be to set the fromStream Position property to 0 prior looping the stream. Learned this from experience when performing a MD5 hash to generate a file checksum prior to saving... The file was created on the IO, but it was always zero bits... Silly me, the position was at the end of the stream when performing my loop...

# December 27, 2010 11:46 PM

kuujinbo said:

Microsoft finally realized they should have included something exactly like this in .NET 4:

Stream.CopyTo Method(Stream)

msdn.microsoft.com/.../dd782932.aspx

Stream.CopyTo Method (Stream, Int32)

msdn.microsoft.com/.../dd783870.aspx

# December 28, 2010 4:18 AM

DigiMortal said:

Thanks for feedback, kuujinbo. .NET Framework 3.5 and 4.0 have this method but this method is not available in some other versions of framework (it doesn't exist in Windows Phone 7 by example).

# December 28, 2010 3:51 PM

I.S.C. Román P.C. said:

That method it's not available in Framework 3.5, only on 4.5. Thanks for the information, very helpful.

# July 27, 2012 5:12 PM