尝试使用 IProgress 和取消令牌创建 ftp 下载异步函数,但在 GetRequestStreamAsync() 函数上出现“ProtocolViolationException:由于对象的当前状态,操作无效”
public async Task DownloadWithProgressAsync(string remoteFilepath, string localFilepath, IProgress<decimal> progress, CancellationToken token)
{
const int bufferSize = 128 * 1024; // 128kb buffer
progress.Report(0m);
var remoteUri = new Uri(_baseUrl + remoteFilepath);
Debug.Log($"Download\nuri: {remoteUri}");
var request = (FtpWebRequest)WebRequest.CreateDefault(remoteUri);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(_username, _password);
token.ThrowIfCancellationRequested();
using (var fileStream = new FileStream(localFilepath, FileMode.OpenOrCreate, FileAccess.Write,
FileShare.Write, bufferSize, true))
{
using (var ftpStream = await request.GetRequestStreamAsync())
{
var buffer = new byte[bufferSize];
int read;
while ((read = await ftpStream.ReadAsync(buffer, 0, buffer.Length, token) ) > 0)
{
await fileStream.WriteAsync(buffer, 0, read, token);
var percent = (decimal)ftpStream.Position / ftpStream.Length;
progress.Report(percent);
}
}
}
var response = (FtpWebResponse)await request.GetResponseAsync();
var success = (int)response.StatusCode >= 200 && (int)response.StatusCode < 300;
response.Close();
if (!success)
throw new Exception(response.StatusDescription);
}