I need to get a list of files from an FTP server.
The FTP server has over 10, 000 files.
I only need the files that start with
int bytesRead = 0;
byte buffer = new byte;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpSourceFilePath);
request.Credentials = new NetworkCredential("anonymous", "email@example.com");
request.Method = WebRequestMethods.Ftp.DownloadFile;
Stream reader = request.GetResponse().GetResponseStream();
FileStream fileStream = new FileStream(localDestinationFilePath, FileMode.Create);
bytesRead = reader.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
fileStream.Write(buffer, 0, bytesRead);
In general, there's no other way than the one you know: retrieve list of all files and filter them locally.
But many servers support non-standard/proprietary filtering of the listing.
If you are lucky and your FTP server do support this, you can use a file mask to retrieve only a subset of files. In your case the mask would by usually like
ABC*. Most major FTP servers do support
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/ABC*"); request.Credentials = new NetworkCredential("username", "password"); request.Method = WebRequestMethods.Ftp.ListDirectory; FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream); Console.WriteLine(reader.ReadToEnd());
For a partial list of supported patterns of common FTP server, see my answer to FTP directory partial listing with wildcards.