How to retrieve just the file names from an FTP site in .NET?
Learn how to retrieve just the list of file names from an FTP site in .NET.
When dealing with a remote FTP before we start downloading those mega files we wanted to exercise extra caution to make sure we don’t unnecessarily put strain on the corporate network. One precautionary way to deal with this is to make sure we download or upload what exactly we want.
Many times, our implementation might require you to just list the files on a page and let the user download what they want. The real download happens only when the user choose a filename. So, how do we get the list of filenames from an FTP site location without downloading the actual file?
Well, .NET has an answer for you with FtpWebRequest on System.Net. FtpWebRequest has a property “Method” which can be used to indicate your intentions with the request, in this case, “ListDirectory”. Once set, a call to GetResponse() will list you the filenames on the FTP location. Of course, when the user chooses to download a file then you can use the “DownloadFile” property to start streaming the file from that FTP site.
Create a simple method that establishes connection with a FTP site (optionally passing-in the parameters).
protected virtual FtpWebRequest CreateFtpWebRequest(Uri uri, string ftpUsername, string ftpPassword)
{
FtpWebRequest ftp = FtpWebRequest.Create(uri) as FtpWebRequest;
if (!(string.IsNullOrEmpty(ftpUsername.Trim())))
{
ftp.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
}
ftp.UseBinary = true;
return ftp;
}
“Uri” parameter takes in a System.Uri with a valid location to a FTP site. If you have the FTP site secured then you can pass-in the “ftpUsername” and “ftpPassword” properties. If you don’t pass-in the values then it will connect to the FTP location as “Anonymous”.
Once you’ve created a FTP request then you can use a similar method like below to get the filenames.
public List
{
List
WebRequest ftpWR = BuildFtpWebRequest(new Uri(remotePath), ftpUsername, ftpPassword);
ftpWR.Method = WebRequestMethods.Ftp.ListDirectory;
using (WebResponse response = ftpWR.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string itme = reader.ReadLine();
while (item != null)
{
result.Add(item);
item = reader.ReadLine();
}
}
return result;
}
Note the usage of the “Method” property on the FTPRequest object. “ListDirectory” indicates that with this request we are intending to get the FTP headers only which will contain the filenames. We then build a list out of it and return the list as List
Technorati Tags:
.NET, How To, FTP, Source Code, Code Sample


