Extension Method to Copy One Stream to Another ~ D. Patrick Caldwell on Software Engineering

Wednesday, March 11, 2009

Extension Method to Copy One Stream to Another

I don't think I could count the number of times I've written this code:
byte[] buffer = new byte[1024];
int bytesRead = 0;

do
{
bytesRead = source.Read(buffer, 0, buffer.Length);
target.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
With my recent cravings for a good reason to write an extension method and the frustration that there's no really good way to read from one stream and write it directly to another, I thought that it'd be really cool if I never had to write these lines of code again in my life!

I looked around and found that the MemoryStream class has a WriteTo(Stream) method. I thought, "I need one of those." At first, I called mine AppendTo(Stream) because I thought that it sounded more like what it was actually going to do. I also didn't know what would happen if I had an extension method with the same signature as an instance method.

I decided I should stop being lazy and look into it. I did some extension method research and found that "an extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself."

So, here's the extension method I ended up with:
public static void WriteTo(this Stream source, Stream target)
{
WriteTo(source, target, 1024);
}

public static void WriteTo(this Stream source, Stream target, int bufferLength)
{
byte[] buffer = new byte[bufferLength];
int bytesRead = 0;

do
{
bytesRead = source.Read(buffer, 0, buffer.Length);
target.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
}
I really appreciate comments so please feel free to comment on my posts. Whether you agree or disagree, I'd love to hear from you. Also, feel free to link back to your own blog in your comments. You can even subscribe to an RSS feed of the comments on this thread.

© 2008 — , D. Patrick Caldwell, President, Autopilot Consulting, LLC

2 comments:

  1. Wow it is so cute and informative,you will be successful with your blog
    please visit my site if you want to know more amazing tips about blogger :
    Zenplate
    Thanks much

    ReplyDelete
  2. Thanks for this - you're absolutely right that no-one should ever have to write this code. This saved me some real annoyance. Thanks again.

    ReplyDelete