ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

CopyTo

Copies a stream to another stream using a passed buffer. it also has an overload to pass a buffer length.

Source

/// <summary>
/// Copies an stream to another stream using the buffer passed.
/// </summary>
/// <param name="source">source stream</param>
/// <param name="destination">destination stream</param>
/// <param name="buffer">buffer to use during copy</param>
/// <returns>number of bytes copied</returns>
public static long CopyTo(this Stream source, Stream destination, byte[] buffer)
{
    long total=0;
    int bytesRead;
    while (true)
    {
        bytesRead = source.Read(buffer, 0, buffer.Length);
        if (bytesRead == 0)
            return total;
        total += bytesRead;
        destination.Write(buffer, 0, bytesRead);
    }
}
/// <summary>
/// Copies an stream to another stream using the buffer with specified size.
/// </summary>
/// <param name="source">source stream</param>
/// <param name="destination">destination stream</param>
/// <param name="bufferLen">length of buffer to create</param>
/// <returns>number of bytes copied</returns>
public static long CopyTo(this Stream source, Stream destination, int bufferLen)
{
    return source.CopyTo(destination, new byte[bufferLen]);
}

Example

Stream fSource=File.OpenRead(@"C:\test.bin");
Stream fDest=File.Create(@"C:\CopyOfTest.bin");
fSource.CopyTo(fDest,10*1024);

Author: Maziar Rezaei

Submitted on: 15 mei 2011

Language: C#

Type: System.IO.Stream

Views: 6215