How To List All Files & Directories From a FTP Server in C#
Friends,
In this post, we will see how we can retrieve the list of files and directories from a FTP server in C#. We will make use of FtpWebRequest class to perform this action. FtpWebRequest class is defined in 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 server “www.server.com” –
private List ListFiles() { try { FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/"); request.Method = WebRequestMethods.Ftp.ListDirectory; request.Credentials = new NetworkCredential("username", "password"); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream); string names = reader.ReadToEnd(); reader.Close(); response.Close(); return names.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList(); } catch (Exception) { throw; } }
In the above code, we create a request to ftp server using 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 FtpWebResponse object. The “ListDirectory” RequestMethod returns all data from server inĀ string format. Finally, we parse the response stream and split the returned data to get a list of all files & folders present on the server’s location.
Hope you like this post! Keep learning & sharing! Cheers!