Created
March 25, 2013 08:47
-
-
Save thecodejunkie/5235757 to your computer and use it in GitHub Desktop.
CopyStreamToStream implemented as an extension method on Stream
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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