//Version taking string/FileInfo public async Task <bool> Download(string sourceFilename, FileInfo targetFI, bool PermitOverwrite) { //1. check target if (targetFI.Exists && !(PermitOverwrite)) { throw (new ApplicationException("Target file already exists")); } //2. check source string target; if (sourceFilename.Trim() == "") { throw (new ApplicationException("File not specified")); } else if (sourceFilename.Contains("/")) { //treat as a full path target = AdjustDir(sourceFilename); } else { //treat as filename only, use current directory target = CurrentDirectory + sourceFilename; } string URI = Hostname + target; //3. perform copy System.Net.FtpWebRequest ftp = await GetRequest(URI); //Set request to download a file in binary mode ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile; ftp.UseBinary = true; //open request and get response stream using (FtpWebResponse response = (FtpWebResponse)await ftp.GetResponseAsync()) { using (Stream responseStream = response.GetResponseStream()) { //loop to read & write to file using (FileStream fs = targetFI.OpenWrite()) { try { byte[] buffer = new byte[2048]; int read = 0; do { read = responseStream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, read); } while (!(read == 0)); responseStream.Close(); fs.Flush(); fs.Close(); } catch (Exception) { //catch error and delete file only partially downloaded fs.Close(); //delete target file as it's incomplete targetFI.Delete(); throw; } } responseStream.Close(); } response.Close(); } return(true); }
private static async Task<bool> TryGetResponseAsync(FtpWebRequest request, FtpStatusCode expectedResult) { for (int attempts = 0; attempts < 5; attempts++) { var response = (FtpWebResponse)await request.GetResponseAsync(); if (response.StatusCode == expectedResult) { return true; } } return false; }