Download all files from a remote FTP directory

Asked

Viewed 695 times

0

I would like your help as I am making an application that downloads files from a remote ftp directory.

Could you pass the code to implement in C# please?

Connect to remote FTP and copy all files from the directory to a local folder on the computer.

1 answer

1


One simple way to do it, when you don’t need so much specific control for this protocol, is to use the class WebClient.

WebClient client = new WebClient();
client.Credentials = new NetworkCredential("usuario", "senha");
client.DownloadFile("ftp://ftp.servidor.com/caminho/arquivo.zip", @"C:\caminho\arquivolocal.zip");

The WebClient will work as it should for this operation. It works for uploading also, using the WebClient.UploadFile(String, String).

If you want to have more control and operations specific to the FTP protocol, use the class FtpWebRequest.

From this, you can download a file from the remote directory. You want to download the entire directory. Just list the files that exist in this directory and download using the WebClient.DownloadFile(String, String) or equivalent. For list the contents of a remote directory:

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
        public static void Main ()
        {
            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/");
            request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential ("anonymous","[email protected]");

            FtpWebResponse response = (FtpWebResponse)request.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();
        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.