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":
- 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 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!

Endri FuciaPosted Oct 9, 2020, 10:35 AM
I think this is a good one but when you call the function you have to use recursion in order to get all files and a parameter for that fuctions zhere to store the name of files.
Arkadeep DePosted Mar 6, 2020, 12:16 PM
Not a useful one, should add recursion to dig down to the last.
Akbar MullaPosted Aug 13, 2018, 7:18 AM
I have an Azure VM. Can i use this to to fetch files ?
Kranthi Vardhan KolluruPosted May 9, 2018, 10:30 PM
Can we use this code for ip address also.? i mean instead of 'ftp://www.server.com/' can i give ip address
Arweb AroshanzamirPosted Jan 23, 2015, 8:08 AM
good job Nitesh Luharuka../ thanks
Manish Kumar ChoudharyPosted Jan 22, 2015, 11:37 PM
Nice one..