forked from NancyFx/Nancy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamExtensions.cs
More file actions
73 lines (64 loc) · 2.39 KB
/
Copy pathStreamExtensions.cs
File metadata and controls
73 lines (64 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
namespace Nancy.Extensions
{
using System;
using System.IO;
/// <summary>
/// Containing extensions for the <see cref="Stream"/> object.
/// </summary>
public static class StreamExtensions
{
/// <summary>
/// Buffer size for copy operations
/// </summary>
internal const int BufferSize = 4096;
/// <summary>
/// Copies the contents between two <see cref="Stream"/> instances in an async fashion.
/// </summary>
/// <param name="source">The source stream to copy from.</param>
/// <param name="destination">The destination stream to copy to.</param>
/// <param name="onComplete">Delegate that should be invoked when the operation has completed. Will pass the source, destination and exception (if one was thrown) to the function. Can pass in <see langword="null" />.</param>
public static void CopyTo(this Stream source, Stream destination, Action<Stream, Stream, Exception> onComplete)
{
var buffer =
new byte[BufferSize];
Action<Exception> done = e =>
{
if (onComplete != null)
{
onComplete.Invoke(source, destination, e);
}
};
AsyncCallback rc = null;
rc = readResult =>
{
try
{
var read =
source.EndRead(readResult);
if (read <= 0)
{
done.Invoke(null);
return;
}
destination.BeginWrite(buffer, 0, read, writeResult =>
{
try
{
destination.EndWrite(writeResult);
source.BeginRead(buffer, 0, buffer.Length, rc, null);
}
catch (Exception ex)
{
done.Invoke(ex);
}
}, null);
}
catch (Exception ex)
{
done.Invoke(ex);
}
};
source.BeginRead(buffer, 0, buffer.Length, rc, null);
}
}
}