0

I want to get the list of files from FTP server with specific search pattern ( Ex: get all the files having pattern as "*.txt") and download these files only using C#.net.

Below is the code returning list of files from FTP server, please suggest the addition code required to achieve the required task.

            FtpWebRequest reqFTP;
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + coldata.Host + "/"));

            //("ftp://" + coldata.host  + "/"));
            reqFTP.UseBinary = true;
            reqFTP.Credentials = new NetworkCredential(coldata.Uid, coldata.Pwd);
            reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
            reqFTP.Timeout = System.Threading.Timeout.Infinite;
            reqFTP.Proxy = null;
            reqFTP.KeepAlive = true;
            reqFTP.UsePassive = true;
            FtpWebResponse res = (FtpWebResponse)reqFTP.GetResponse();
            response = reqFTP.GetResponse();
            reader = new StreamReader(response.GetResponseStream());
            string line = reader.ReadLine();
            while (line != null)
            {
                result.Append(line);
                result.Append("\n");
                line = reader.ReadLine();
            }
            // to remove the trailing '\n'
            result.Remove(result.ToString().LastIndexOf('\n'), 1);
            downloadRes = true;
            return result.ToString().Split('\n');

Thanks.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Murtaza Badshah
  • 211
  • 2
  • 5
  • 11

1 Answers1

1

You could use System.IO.Path.GetExtension, something like this maybe:

while (line != null)
{
    if (System.IO.Path.GetExtension(line) == "txt")
    {
        result.Append(line);
        result.Append("\n");
        line = reader.ReadLine();
    }
}

Not exactly what you asked for, but you cannot specify search patterns for FTP, see here:

how to fetch a range of files from an FTP server using C#

Community
  • 1
  • 1
Ashigore
  • 4,618
  • 1
  • 19
  • 39
  • @code4life Please give an example then, because the FTP standard doesn't support it and several different ftp servers I tested didn't work. – Ashigore Apr 08 '16 at 20:08