/// <summary> /// Show toast notification when a file is downloaded. /// </summary> async void FTPItem_DownloadCompleted(object sender, FTP.DownloadCompletedEventArgs e) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { if (e.Error == null) { progressInfo.Items.Insert(0, string.Format("{0} is completed.", e.RequestFile.ToString())); } else { progressInfo.Items.Insert(0, string.Format("{0} is not completed: {1}.", e.RequestFile.ToString(), e.Error.Message)); } progressInfo.SelectedIndex = 0; } ); }
/// <summary> /// Download a single file from FTP server using WebRequest. /// </summary> public static async Task <DownloadCompletedEventArgs> DownloadFTPFileAsync(FTPFileSystem item, StorageFile targetFile, ICredentials credential) { var result = new DownloadCompletedEventArgs { RequestFile = item.Url, LocalFile = targetFile, Error = null }; // This request is FtpWebRequest in fact. WebRequest request = WebRequest.Create(item.Url); if (credential != null) { request.Credentials = credential; } request.Proxy = WebRequest.DefaultWebProxy; // Set the method to Download File request.Method = "RETR"; try { // Open the file for write. using (IRandomAccessStream fileStream = await targetFile.OpenAsync(FileAccessMode.ReadWrite)) { // Get response. using (WebResponse response = await request.GetResponseAsync()) { // Get response stream. using (Stream responseStream = response.GetResponseStream()) { byte[] downloadBuffer = new byte[2048]; int bytesSize = 0; // Download the file until the download is completed. while (true) { // Read a buffer of data from the stream. bytesSize = responseStream.Read(downloadBuffer, 0, downloadBuffer.Length); if (bytesSize == 0) { break; } // Write buffer to the file. await fileStream.WriteAsync(downloadBuffer.AsBuffer()); } } } } } catch (Exception ex) { result.Error = ex; } return(result); }