Wednesday, 9 June 2010

Fed up with writing methods to copy one stream to another

I constantly find myself writing static methods in my applications to copy one stream into another so I finally decided  to add an extension method to our internal library. There is a method on the MemoryStream class called WriteTo which does this but I wanted it to be available to all instances of Stream.
public static void CopyTo(this Stream input, Stream output, int bufferSize)
    Validate.Argument(() => input).IsNotNull().Satisifes(stream => stream.CanRead);
    Validate.Argument(() => output).IsNotNull().Satisifes(stream => stream.CanWrite);
    Validate.Argument(() => bufferSize).IsGreaterThan(0);var buffer = new byte[bufferSize];
    int len;
    while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
        output.Write(buffer, 0, len);
public static void CopyTo(this Stream input, Stream output)
    input.CopyTo(output, 4096);

The validation at the top uses a custom library but basically it is checking that both the streams are not null, that the input stream can be read and the output stream can be written to. Apart from that the code is just the bog standard off the shelf code that copies one stream to another.

Initially my method was called Copy but I found out afterwards that Microsoft has already added a method to the Stream class in .net 4.0 which does exactly this so to be consistent I have given it the same name, CopyTo. This also has the benefit of being able to port any code that uses this to .net 4.0 and it will pickup the method on the Stream class without making any changes as extension methods are given the lowest priority.

1 comment:

  1. The Best Casino Games For The Spins - Dr. Maryland
    The best casino games for players who want 동해 출장안마 to try different games 광주 출장안마 in 제천 출장안마 the casino. In the past, online 의정부 출장샵 casinos have been offering players the 김포 출장마사지 ability to