byte[] buffer = new byte[1024];
int bytesRead = 0;
do
{
bytesRead = source.Read(buffer, 0, buffer.Length);
target.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
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);
}
Wow it is so cute and informative,you will be successful with your blog
ReplyDeleteplease visit my site if you want to know more amazing tips about blogger :
Zenplate
Thanks much
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