How To List All Files & Directories From a FTP Server in C#

In this article, we will see how to retrieve the list of files and directories from a FTP server in C#. We will use the FtpWebRequest class to perform this action. The FtpWebRequest class is defined in the System.Net namespace. This means you need to use this namespace at the top of your program to use the FtpWebRequest class.

Let's see a code sample to retrieve the list of files and directories from the root folder of the server "www.server.com":

  1. private List ListFiles()  
  2. {  
  3.     try  
  4.     {  
  5.          FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/");  
  6.          request.Method = WebRequestMethods.Ftp.ListDirectory;  
  7.   
  8.          request.Credentials = new NetworkCredential("username""password");  
  9.          FtpWebResponse response = (FtpWebResponse)request.GetResponse();  
  10.          Stream responseStream = response.GetResponseStream();  
  11.          StreamReader reader = new StreamReader(responseStream);  
  12.          string names = reader.ReadToEnd();  
  13.   
  14.          reader.Close();  
  15.          response.Close();  
  16.   
  17.          return names.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();  
  18.     }  
  19.     catch (Exception)  
  20.     {  
  21.         throw;  
  22.     }  

In the preceding code, we create a request to a FTP server using the FtpWebRequest class and set the RequestMethod of the request to WebRequestMethods.Ftp.ListDirectory. In the next line, we define the credentials to be used on the server. Then we fire the request and get the response in the FtpWebResponse object. The "ListDirectory" RequestMethod returns all the data from the server in string format. Finally, we parse the response stream and split the returned data to get a list of all the files and folders present on the server's location.

I hope you like this article! Keep learning and sharing! Cheers!