Skip to content

Instantly share code, notes, and snippets.

@Virtlink
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Virtlink/9337057 to your computer and use it in GitHub Desktop.
Save Virtlink/9337057 to your computer and use it in GitHub Desktop.
Copies part of a stream to another stream.
using System;
using System.Diagnostics.Contracts;
using System.IO;
namespace Virtlink
{
/// <summary>
/// Extension methods for <see cref="Stream"/> objects.
/// </summary>
/// <example>
/// Usage example:
/// <code>
/// string inputFilename = @"input.bin";
/// string outputFilename = @"output.bin";
/// using (var input = File.OpenRead(inputFilename))
/// using (var output = File.Create(outputFilename))
/// {
/// input.Seek(0x1000, SeekOrigin.Begin);
/// input.CopyPartTo(output, 0x2000);
/// }
/// </code>
/// </example>
/// <remarks>
/// Created by Virtlink. Original source code on GitHub:
/// <see href="https://gist.github.com/Virtlink/9337057"/>.
/// </remarks>
public static class StreamExtensions
{
/// <summary>
/// Copies a specific number of bytes from the current position of the
/// source stream to the current position of the destination stream.
/// </summary>
/// <param name="source">The source stream.</param>
/// <param name="destination">The destination stream.</param>
/// <param name="count">The number of bytes to copy.</param>
/// <param name="bufferSize">The size of the buffer to use.
/// The default is 4096.</param>
public static void CopyPartTo(this Stream source, Stream destination, int count, int bufferSize)
{
#region Contract
Contract.Requires<ArgumentNullException>(source != null);
Contract.Requires<ArgumentNullException>(destination != null);
Contract.Requires<ArgumentOutOfRangeException>(count >= 0);
Contract.Requires<ArgumentOutOfRangeException>(bufferSize > 0);
#endregion
byte[] buffer = new byte[bufferSize];
int read;
while (count > 0 && (read = source.Read(buffer, 0, Math.Min(buffer.Length, count))) > 0)
{
count -= read;
destination.Write(buffer, 0, read);
}
}
/// <summary>
/// Copies a specific number of bytes from the current position of the
/// source stream to the current position of the destination stream.
/// </summary>
/// <param name="source">The source stream.</param>
/// <param name="destination">The destination stream.</param>
/// <param name="count">The number of bytes to copy.</param>
public static void CopyPartTo(this Stream source, Stream destination, int count)
{
#region Contract
Contract.Requires<ArgumentNullException>(source != null);
Contract.Requires<ArgumentNullException>(destination != null);
Contract.Requires<ArgumentOutOfRangeException>(count >= 0);
#endregion
CopyPartTo(source, destination, count, 0x1000);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment