The Inquisitive Coder – Davy Brion's Blog

Trying to walk that thin line between intelligence and ignorance

Stream.CopyTo method

Posted by Davy Brion on April 29th, 2008

No, Stream does not have a useful CopyTo method :(

unless…. :

    public static class Extensions

    {

        public static void CopyTo(this Stream source, Stream target)

        {

            if (!source.CanRead) throw new ArgumentException(“source can not be read”, “source”);

            if (!target.CanWrite) throw new ArgumentException(“target can not be written to”, “target”);

 

            source.Position = 0;

 

            while (source.Position < source.Length)

            {

                var buffer = new byte[4096];

                int bytesRead = source.Read(buffer, 0, buffer.Length);

                target.Write(buffer, 0, bytesRead);

            }

        }

    }

now you can do:

stream.CopyTo(fileStream);

If there is a way to copy the contents of one stream to another in the .NET framework, please let me know ;)

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>