How to Download Numerous Files from FTP using C#?

SidC picture SidC · Aug 7, 2013 · Viewed 17.5k times · Source

I need to run a console application at scheduled intervals that needs to download only .pgp files from an FTP site. Any pgp file in the FTP must be downloaded. I've found the sample code to get a directory listing of the FTP and have written that here:

FtpWebRequest req = (FtpWebRequest)WebRequest.Create("ftp://ourftpserver");
        req.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

        req.Credentials = new NetworkCredential("user", "pass");

        FtpWebResponse response = (FtpWebResponse)req.GetResponse();

        Stream responseStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(responseStream);
        Console.WriteLine(reader.ReadToEnd());

        Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription);

        reader.Close();
        response.Close();

What must I do to download all files of the type .pgp from the directory listing and save them in a local directory on our server?

Answer

Jim Mischel picture Jim Mischel · Aug 7, 2013

The FtpWebRequest and FtpWebResponse objects are really designed do make single requests (i.e. download single files, etc.)

You're looking for an FTP client. There isn't one in the .NET Framework, but there's a free one, System.Net.FtpClient that apparently works quite well.