Skip to main content

Note: This post is part of a series and you can find the rest of the parts in the series index.

Streams are something I try to avoid, it feels to me like I am getting down and dirty when I use them – but maybe that is just flash backs to working in Delphi :) They are very useful, but they can be clunky especially when you need to get the content into another stream.

The key example of coping a steam is when you write your own file copy method (and which programmer hasn’t):

using (FileStream sourceFile = new FileStream("test.xml", FileMode.Open))
{
    using (FileStream destinationFile = new FileStream("target.xml", FileMode.Create))
    {
        byte[] buffer = new byte[4096];
        int read;
        while ((read = sourceFile.Read(buffer, 0, buffer.Length)) != 0)
        {
            destinationFile.Write(buffer, 0, read);
        }
    }
}

The whole buffer/read/write pattern is just ugly.

Now with .NET 4, we can use the new CopyTo method to fix this up:

using (FileStream sourceFile = new FileStream("test.xml", FileMode.Open))
{
    using (FileStream destinationFile = new FileStream("target.xml", FileMode.Create))
    {
        sourceFile.CopyTo(destinationFile);
    }
}

Ah, much better!