Skip to content

Instantly share code, notes, and snippets.

@thecodejunkie
Created March 25, 2013 08:47
Show Gist options
  • Save thecodejunkie/5235757 to your computer and use it in GitHub Desktop.
Save thecodejunkie/5235757 to your computer and use it in GitHub Desktop.
CopyStreamToStream implemented as an extension method on Stream
public static class StreamExtensions
{
public static void CopyStreamToStream(this Stream source, Stream destination, Action<Stream, Stream, Exception> completed)
{
var buffer = new byte[4096];
var operation =
AsyncOperationManager.CreateOperation(null);
Action<Exception> done = e =>
{
if (completed != null)
{
operation.Post(state => completed(source, destination, e), null);
}
};
AsyncCallback rc = null;
rc = readResult =>
{
try
{
var read =
source.EndRead(readResult);
if (read <= 0)
{
done(null);
}
destination.BeginWrite(buffer, 0, read, writeResult =>
{
try
{
destination.EndWrite(writeResult);
source.BeginRead(buffer, 0, buffer.Length, rc, null);
}
catch (Exception ex)
{
done(ex);
}
}, null);
}
catch (Exception ex)
{
done(ex);
}
};
source.BeginRead(buffer, 0, buffer.Length, rc, null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment