.NET 4 Baby Steps: Part IX - Stream

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—they feel to me like I’m getting down and dirty when I use them—but maybe that’s just flashbacks to working in Delphi. 😉 They’re very useful, though, and can be clunky, especially when you need to get the content into another stream.

The key example of copying a stream 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 clean 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!