@@ -14,6 +14,31 @@ public class DownloadClient : IDisposable
1414 public delegate void DownloadClientEventHandler ( object source , int percentage ) ;
1515 public event DownloadClientEventHandler DownloadProgressChanged ;
1616
17+ private void copyStreamWithProgress ( Stream inputStrem , Stream outputStream )
18+ {
19+ long streamLength = inputStrem . Length ;
20+ long totalBytesRead = 0 ;
21+ byte [ ] buffer = new byte [ 1024 ] ;
22+ int bytesRead = 0 ;
23+ int percentageDownloaded = 0 ;
24+ int percentage ;
25+
26+ while ( ( bytesRead = inputStrem . Read ( buffer , 0 , buffer . Length ) ) > 0 )
27+ {
28+ outputStream . Write ( buffer , 0 , bytesRead ) ;
29+
30+ // only trigger event when percentage has changed
31+ percentage = ( int ) ( ( double ) totalBytesRead / ( double ) streamLength * 100.0 ) ;
32+ if ( percentageDownloaded != percentage )
33+ {
34+ percentageDownloaded = percentage ;
35+ DownloadProgressChanged ? . Invoke ( this , percentage ) ;
36+ }
37+
38+ totalBytesRead += bytesRead ;
39+ }
40+ }
41+
1742 public DownloadClient ( string url )
1843 {
1944 httpClient . Timeout = TimeSpan . FromMinutes ( 5 ) ;
@@ -55,44 +80,24 @@ public void DownloadToFile(string file)
5580 using ( var downloadStream = response . Content . ReadAsStreamAsync ( ) . Result )
5681 using ( var fileStream = new FileStream ( file , FileMode . Create ) )
5782 {
58- long streamLength = downloadStream . Length ;
59- long totalBytesRead = 0 ;
60- byte [ ] buffer = new byte [ 1024 ] ;
61- int bufferLength = 0 ;
62- int percentageDownloaded = 0 ;
63- int percentage = 0 ;
64-
65- while ( ( bufferLength = downloadStream . Read ( buffer , 0 , buffer . Length ) ) > 0 )
66- {
67- fileStream . Write ( buffer , 0 , bufferLength ) ;
68-
69- // only trigger event when percentage has changed
70- percentage = ( int ) ( ( double ) totalBytesRead / ( double ) streamLength * 100.0 ) ;
71- if ( percentageDownloaded != percentage )
72- {
73- percentageDownloaded = percentage ;
74- DownloadProgressChanged ? . Invoke ( this , percentage ) ;
75- }
76-
77- totalBytesRead += bufferLength ;
78- }
83+ copyStreamWithProgress ( downloadStream , fileStream ) ;
7984 }
8085 }
8186
8287 public MemoryStream DownloadToMemory ( )
8388 {
84- MemoryStream memoryStream = new MemoryStream ( ) ;
85-
8689 var response = httpClient . SendAsync ( httpRequestMessage ) . Result ;
8790
8891 if ( ! response . IsSuccessStatusCode )
8992 {
9093 throw new HttpRequestException ( $ "Received unsuccessful status code: { ( int ) response . StatusCode } { response . StatusCode } ") ;
9194 }
9295
96+ MemoryStream memoryStream ;
9397 using ( var downloadStream = response . Content . ReadAsStreamAsync ( ) . Result )
9498 {
95- downloadStream . CopyTo ( memoryStream ) ;
99+ memoryStream = new MemoryStream ( ( int ) downloadStream . Length ) ;
100+ copyStreamWithProgress ( downloadStream , memoryStream ) ;
96101 }
97102
98103 return memoryStream ;
0 commit comments