-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathStreamUtils.cs
More file actions
33 lines (29 loc) · 1.14 KB
/
StreamUtils.cs
File metadata and controls
33 lines (29 loc) · 1.14 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
using System.IO;
namespace ModApi.Common
{
public class StreamUtils
{
public delegate void StreamProgressEventHandler(object source, int percentage);
public static void CopyStreamWithProgress(Stream inputStrem, Stream outputStream, object eventSource, StreamProgressEventHandler eventHandler)
{
long streamLength = inputStrem.Length;
byte[] buffer = new byte[4096];
long totalBytesRead = 0;
int bytesRead;
int percentageDownloaded = 0;
int percentage;
while ((bytesRead = inputStrem.Read(buffer, 0, buffer.Length)) > 0)
{
outputStream.Write(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
// only trigger event when percentage has changed
percentage = (int)((double)totalBytesRead / (double)streamLength * 100.0);
if (percentageDownloaded != percentage)
{
percentageDownloaded = percentage;
eventHandler?.Invoke(eventSource, percentage);
}
}
}
}
}