aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Controller/IO/StreamHelper.cs
blob: 5aec9a1828c312a9fb7ac6da7d87b7a2bc917c2f (plain)
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
using System.IO;
using System.Threading;
using System;
using System.Threading.Tasks;

namespace MediaBrowser.Controller.IO
{
    public static class StreamHelper
    {
        public static void CopyTo(Stream source, Stream destination, int bufferSize, Action onStarted, CancellationToken cancellationToken)
        {
            byte[] buffer = new byte[bufferSize];
            int read;
            while ((read = source.Read(buffer, 0, buffer.Length)) != 0)
            {
                cancellationToken.ThrowIfCancellationRequested();

                destination.Write(buffer, 0, read);

                if (onStarted != null)
                {
                    onStarted();
                    onStarted = null;
                }
            }
        }

        public static async Task CopyToAsync(Stream source, Stream destination, int bufferSize, IProgress<double> progress, long contentLength, CancellationToken cancellationToken)
        {
            byte[] buffer = new byte[bufferSize];
            int read;
            long totalRead = 0;

            while ((read = source.Read(buffer, 0, buffer.Length)) != 0)
            {
                cancellationToken.ThrowIfCancellationRequested();

                destination.Write(buffer, 0, read);

                totalRead += read;

                double pct = totalRead;
                pct /= contentLength;
                pct *= 100;

                progress.Report(pct);
            }
        }
    }
}