Download all files from a remote FTP directory

0

I would like your help because 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.

    
asked by anonymous 14.11.2017 / 18:35

1 answer

1

A simple way to do this, when you do not need so much specific control for this protocol, is to use the WebClient .

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

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

If you want to have greater control and specific FTP protocol operations, use the 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 WebClient.DownloadFile(String, String) or equivalent. To 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();
        }
    }
}
    
15.11.2017 / 00:23