Stream.CopyTo method

No Comments »Written on April 29th, 2008 by
Categories: Software Development

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