In this post I will discuss how to use FtpWebRequest class to download a file from a FTP location. The code makes use of GetResponse method to get response as byte array. You can argue about why not use DownloadFile method on WebClient. There are certain issues with use of this method. This method does not provide a lot of control on request. For example if the file is large, your request could time out. Or if you do not want process to block the request for long time, you will not be able to control it. By setting Timeout property, you can indicate when to terminate request of it is taking too long. Use of FtpWebRequest allows you to set more options on the request to control its behavior.
static string DownloadDataFromFtp(string sourceFileLocation) { var uri = new Uri(sourceFileLocation); var ftpClient = FtpWebRequest.CreateDefault(uri); ftpClient.Timeout = 15000; var response = ftpClient.GetResponse() as FtpWebResponse; string ftpdata = string.Empty; try { ftpdata = ProcessFtpContent(response); } finally { response.Close(); } return ftpdata; } static string ProcessFtpContent(FtpWebResponse resp) { string content = string.Empty; MemoryStream memStream = new MemoryStream(); const int BUFFER_SIZE = 4096; int read = 0; int idx = 0; long size = 0; memStream.SetLength(BUFFER_SIZE); try { using (memStream) { while (true) { read = 0; byte[] respBuffer = new byte[BUFFER_SIZE]; read = resp.GetResponseStream().Read(respBuffer, 0, BUFFER_SIZE); if (read == 0) { break; } size += read; memStream.SetLength(size); memStream.Write(respBuffer, 0, read); idx += read; } content = System.Text.Encoding.UTF8.GetString(memStream.ToArray()); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("ProcessContent[Failed]: {0} ", ex.Message); throw; } return content; }
Internet Explorer file download error with SSL enabled web site
0x1F is an invalid start of a value
Learn Python: How to ignore SSL verification for HTTP requests
How to host your web site from your home
Automate testing of web page element transition with Selenium
Alert and Confirm pop up using BootBox in AngularJS
AngularJS Grouped Bar Chart and Line Chart using D3
How to lock and unlock account in Asp.Net Identity provider
2022 © Byteblocks, ALL Rights Reserved. Privacy Policy | Terms of Use