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

WriteTo

Writes the entire contents of this stream to another stream using a buffer.

Source

private const int DefaultBufferSize = 0x1000;

/// <summary>
/// Writes the entire contents of this stream to another stream using a buffer.
/// </summary>
/// <param name="sourceStream">The source stream.</param>
/// <param name="stream">The stream to write this stream to.</param>
/// <param name="bufferSize">Size of the buffer.</param>
/// <remarks>
/// The size of the buffer is 4096 bytes
/// </remarks>
public static void WriteTo(this Stream sourceStream, Stream stream)
{
    WriteTo(sourceStream, stream, DefaultBufferSize);
}

/// <summary>
/// Writes the entire contents of this stream to another stream using a buffer
/// with the specified size.
/// </summary>
/// <param name="sourceStream">The source stream.</param>
/// <param name="stream">The stream to write this stream to.</param>
/// <param name="bufferSize">Size of the buffer.</param>
public static void WriteTo(this Stream sourceStream, Stream stream, int bufferSize)
{
    byte[] buffer = new byte[bufferSize];
    int n;
    while ((n = sourceStream.Read(buffer, 0, buffer.Length)) != 0)
        stream.Write(buffer, 0, n);

}

Example

public static void CompressTo(Stream sourceStream, Stream stream)
{
    using (GZipStream zipStream = new GZipStream(stream, CompressionMode.Compress, true))
        sourceStream.WriteTo(zipStream);
}

Author: Magnus Persson

Submitted on: 1 jun. 2009

Language: C#

Type: System.IO.Stream

Views: 4788