Read Multiple Files From Folder And Download Using FTP location In Console Application Using C#

Introduction

  • Here, I will explain how to read multiple files from the folder, using FTP location. Please follow the steps mentioned below to fetch.
  • Follow the steps mentioned below to achieve our requirement.
Step 1
  •  Place the code in Class file
  1. string ftpDownloadResult = string.Empty;  
  2.   
  3. try  
  4.   
  5. {  
  6.   
  7.  WebRequest request = WebRequest.Create(ConfigurationManager.AppSettings["FTPPath"]);  
  8.   
  9.  request.Method = WebRequestMethods.Ftp.ListDirectory;  
  10.   
  11.  request.Credentials = newNetworkCredential(ConfigurationManager.AppSettings["FTPUserName"],  
  12.   
  13.   ConfigurationManager.AppSettings["FTPPassword"]);  
  14.   
  15.  using(var response = (FtpWebResponse) request.GetResponse())  
  16.   
  17.  {  
  18.   
  19.   StreamReader streamReader = newStreamReader(response.GetResponseStream());  
  20.   
  21.   List < string > directories = newList < string > ();  
  22.   
  23.   string line = streamReader.ReadLine();  
  24.   
  25.   while (!string.IsNullOrEmpty(line))  
  26.   
  27.   {  
  28.   
  29.    directories.Add(line);  
  30.   
  31.    line = streamReader.ReadLine();  
  32.   
  33.   }  
  34.   
  35.   streamReader.Close();  
  36.   
  37.   using(WebClient ftpClient = newWebClient())  
  38.   
  39.   {  
  40.   
  41.    ftpClient.Credentials =  
  42.   
  43.   
  44.   
  45.     new System.Net.NetworkCredential(  
  46.   
  47.      ConfigurationManager.AppSettings["FTPUserName"],  
  48.   
  49.      ConfigurationManager.AppSettings["FTPPassword"]);  
  50.   
  51.    for (int i = 0; i <= directories.Count– 1; i++)  
  52.   
  53.    {  
  54.   
  55.     if (directories[i].Contains(“.”))  
  56.   
  57.     {  
  58.   
  59.      string path = ConfigurationManager.AppSettings["FTPPath"] + directories[i].ToString();  
  60.   
  61.      string trnsfrpth = ConfigurationManager.AppSettings["SaveFilePath"] + directories[i].ToString();  
  62.   
  63.      ftpClient.DownloadFile(path, trnsfrpth);  
  64.   
  65.     }  
  66.   
  67.    }  
  68.   
  69.   }  
  70.   
  71.  }  
Step 2
  •  Add the code, mentioned below to app.config
  1. <appSettings> < add key="FTPPath" value="ftp://test.com/MyFolder"></add> < add key="FTPUserName" value="USERNAME" /> <add key="FTPPassword" value="PASSWORD" />  
  2.   
  3. <addkeyaddkey="SaveFilePath"value="C:\HRData\" />  
  4.   
  5. < /appSettings>  
  6.   
  7. <system.net> < defaultProxy useDefaultCredentials="true"> <proxy autoDetect="True"/> < /defaultProxy> < /system.net>  
Ebook Download
View all
Learn
View all