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();
}
}
}