Recently someone asked me how to download multiple files from an FTP using wildcards. While I started looking for an answer I found out that is not possible using the FTPWebRequest class. The good news is that although downloading using wildcards is not supported, wilcards are supported for listing files on a directory. This leaves us with one choice: first we get a list of files to download and then we download them one by one. Below is the code, I hope this helps you...
public void DownloadFiles(string WildCard)
{
//WildCard = "*Parts.csv"
string[] Files = GetFiles(WildCard);
foreach (string file in Files)
{
DownloadFile(file);
}
}
private string[] GetFiles(string WildCard)
{
string ReturnStr = "";
//Connect to the FTP
FtpWebRequest request = WebRequest.Create("ftp://localhost/Completed/" + WildCard) as FtpWebRequest;
//Specify we're Listing a directory
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential("SomeUser", SomePassword
StringWriter sw = new StringWriter();
//Get a reponse
WebResponse response = request.GetResponse();
Stream responseStream = response.GetResponseStream();
//Convert the response to a string
int ch;
while ((ch = responseStream.ReadByte()) != -1)
ReturnStr = ReturnStr + Convert.ToChar(ch);
//clean up
responseStream.Close();
response.Close();
//split the string by new line
string[] sep = {"\r\n"};
string[] Files = ReturnStr.Split(sep, StringSplitOptions.RemoveEmptyEntries);
return Files;
}
private void DownloadFile(string FileName)
{
//Connect to the FTP
FtpWebRequest request = WebRequest.Create("ftp://lcalhost/Completed/" + FileName) as FtpWebRequest;
//Specify we're downloading a file
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential("SomeUser", "SomePassword");
//initialize the Filestream we're using to create the downloaded file locally
FileStream localfileStream = new FileStream(@"c:\Data\" + FileName, FileMode.Create, FileAccess.Write);
//Get a reponse
WebResponse response = request.GetResponse();
Stream responseStream = response.GetResponseStream();
//create the file
byte[] buffer = new byte[1024];
int bytesRead = responseStream.Read(buffer, 0, 1024);
while (bytesRead != 0)
{
localfileStream.Write(buffer, 0, bytesRead);
bytesRead = responseStream.Read(buffer, 0, 1024);
}
//clean up
localfileStream.Close();
response.Close();
responseStream.Close();
}
Happy Programming!