Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. public sealed class WebClientFileDownloader : IFileDownloader
  2. {
  3. private NetworkCredential _networkCredentials;
  4. public string UserName => _networkCredentials.UserName;
  5. public string Password => _networkCredentials.Password;
  6. public string Host { get; private set; }
  7.  
  8. public WebClientFileDownloader(string host, string userName = null, string password = null)
  9. {
  10. _networkCredentials = new NetworkCredential(userName, password);
  11. Host = host;
  12. }
  13.  
  14. public async Task DownloadFileAsync(FullFileInfo fullFileInfo, CancellationToken cancellationToken, IProgress<double> progress)
  15. {
  16. Task downloadingTask = DownloadFileAsync(fullFileInfo.LocalFileInfo, fullFileInfo.FtpFileInfo, cancellationToken, progress);
  17. await Task.WhenAny(downloadingTask, Task.Delay(int.MaxValue, cancellationToken));
  18. }
  19.  
  20. private async Task DownloadFileAsync(FileInfo localFileInfo, FtpFileInfo ftpFileInfo, CancellationToken cancellationToken, IProgress<double> progress)
  21. {
  22. FileInfo tempLocalFile = new FileInfo(localFileInfo.FullName + "_temp" + DateTime.UtcNow.Ticks);
  23. Debug.Log(tempLocalFile.FullName);
  24.  
  25. try
  26. {
  27. using (WebClient client = new WebClient() { Credentials = _networkCredentials })
  28. using (cancellationToken.Register(() =>
  29. {
  30. Debug.Log("Отменю текущую загрузку");
  31. client.CancelAsync();
  32. Debug.Log("Отменил текущую загрузку");
  33. }))
  34. {
  35. client.DownloadProgressChanged += (s, e) =>
  36. progress.Report(e.BytesReceived / (double)ftpFileInfo.Size * 100D);
  37.  
  38. Uri url = new Uri(new Uri("ftp://" + Host), ftpFileInfo.FullName);
  39. await client.DownloadFileTaskAsync(url, tempLocalFile.FullName);
  40. tempLocalFile.MoveTo(localFileInfo.FullName);
  41. }
  42. }
  43. catch (Exception exc)
  44. {
  45. Debug.LogException(exc);
  46. tempLocalFile.DeleteIfExists();
  47. }
  48. Debug.Log("Выхожу из метода загрузки");
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement