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.

No comments:

Post a Comment