22using System . Diagnostics ;
33using System . IO ;
44using System . Net . Http ;
5+ using System . Threading ;
56using System . Threading . Tasks ;
67
78namespace WebApiClient
@@ -46,14 +47,26 @@ public HttpResponseFile(HttpResponseMessage response)
4647 this . FileName = headers . ContentDisposition ? . FileName ;
4748 this . MediaType = headers . ContentType ? . MediaType ;
4849 }
49-
5050 /// <summary>
5151 /// 保存到指定路径
5252 /// </summary>
5353 /// <param name="filePath">文件路径和文件名</param>
5454 /// <exception cref="ArgumentNullException"></exception>
5555 /// <returns></returns>
5656 public async Task SaveAsAsync ( string filePath )
57+ {
58+ await this . SaveAsAsync ( filePath , CancellationToken . None ) ;
59+ }
60+
61+ /// <summary>
62+ /// 保存到指定路径
63+ /// </summary>
64+ /// <param name="filePath">文件路径和文件名</param>
65+ /// <param name="cancellationToken">取消令牌</param>
66+ /// <exception cref="ArgumentNullException"></exception>
67+ /// <exception cref="OperationCanceledException"></exception>
68+ /// <returns></returns>
69+ public async Task SaveAsAsync ( string filePath , CancellationToken cancellationToken )
5770 {
5871 if ( string . IsNullOrEmpty ( filePath ) == true )
5972 {
@@ -68,7 +81,7 @@ public async Task SaveAsAsync(string filePath)
6881
6982 using ( var fileStream = new FileStream ( filePath , FileMode . OpenOrCreate , FileAccess . Write ) )
7083 {
71- await this . SaveAsAsync ( fileStream ) . ConfigureAwait ( false ) ;
84+ await this . SaveAsAsync ( fileStream , cancellationToken ) . ConfigureAwait ( false ) ;
7285 }
7386 }
7487
@@ -80,6 +93,20 @@ public async Task SaveAsAsync(string filePath)
8093 /// <exception cref="ArgumentException"></exception>
8194 /// <returns></returns>
8295 public async Task SaveAsAsync ( Stream stream )
96+ {
97+ await this . SaveAsAsync ( stream , CancellationToken . None ) . ConfigureAwait ( false ) ;
98+ }
99+
100+ /// <summary>
101+ /// 保存到目标流
102+ /// </summary>
103+ /// <param name="stream">流</param>
104+ /// <param name="cancellationToken">取消令牌</param>
105+ /// <exception cref="ArgumentNullException"></exception>
106+ /// <exception cref="ArgumentException"></exception>
107+ /// <exception cref="OperationCanceledException"></exception>
108+ /// <returns></returns>
109+ public async Task SaveAsAsync ( Stream stream , CancellationToken cancellationToken )
83110 {
84111 if ( stream == null )
85112 {
@@ -96,6 +123,8 @@ public async Task SaveAsAsync(Stream stream)
96123
97124 while ( true )
98125 {
126+ cancellationToken . ThrowIfCancellationRequested ( ) ;
127+
99128 var length = await sourceStream . ReadAsync ( buffer , 0 , buffer . Length ) . ConfigureAwait ( false ) ;
100129 var isCompleted = length == 0 ;
101130
0 commit comments