Carica e scarica un file sul / dal server FTP in C # /. NET

Jun 17 2017

Sto usando .NET 4 C #. Sto cercando di caricare e quindi scaricare un file ZIP sul (mio) server.

Per il caricamento ho

using (WebClient client = new WebClient())
{
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(MyUrl);
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.EnableSsl = false;
    request.Credentials = new NetworkCredential(MyLogin, MyPassword);
    byte[] fileContents = null;
    using (StreamReader sourceStream = new StreamReader(LocalFilePath))
    {
        fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
    }
    request.ContentLength = fileContents.Length;
    using (Stream requestStream = request.GetRequestStream())
    {
        requestStream.Write(fileContents, 0, fileContents.Length);
    }
    FtpWebResponse response = null;
    response = (FtpWebResponse)request.GetResponse();
    response.Close();
}

Questo sembra funzionare, in quanto ottengo un file sul server della giusta dimensione.

1) Come posso trasmetterlo in streaming, invece di caricarlo prima in memoria? Caricherò file molto grandi.

E per il download ho

using (WebClient client = new WebClient())
{
    string HtmlResult = String.Empty;
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(remoteFile);
    request.Method = WebRequestMethods.Ftp.DownloadFile;
    request.EnableSsl = false;
    request.Credentials = new NetworkCredential(MyLogin, MyPassword);
    using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
    using (Stream responseStream = response.GetResponseStream())
    using (StreamReader reader = new StreamReader(responseStream))
    using (FileStream writer = new FileStream(localFilename, FileMode.Create))
    {
        long length = response.ContentLength;
        int bufferSize = 2048;
        int readCount;
        byte[] buffer = new byte[2048];
        readCount = responseStream.Read(buffer, 0, bufferSize);
        while (readCount > 0)
        {
            writer.Write(buffer, 0, readCount);
            readCount = responseStream.Read(buffer, 0, bufferSize);
        }
    }
}

2) Tutto sembra funzionare ... tranne quando provo a decomprimere il file ZIP scaricato ottengo un file ZIP non valido.

Risposte

16 MartinPrikryl Jun 17 2017 at 19:20

Caricare

Il modo più semplice per caricare un file binario su un server FTP utilizzando .NET framework è utilizzare WebClient.UploadFile:

WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.UploadFile(
    "ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");

Se hai bisogno di un controllo maggiore, che WebClientnon offre (come la crittografia TLS / SSL , ecc.), Usa FtpWebRequest. Il modo semplice è copiare un FileStreamflusso su FTP utilizzando Stream.CopyTo:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.UploadFile;  

using (Stream fileStream = File.OpenRead(@"C:\local\path\file.zip"))
using (Stream ftpStream = request.GetRequestStream())
{
    fileStream.CopyTo(ftpStream);
}

Se è necessario monitorare l'avanzamento di un caricamento, è necessario copiare i contenuti in blocchi da soli:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.UploadFile;  

using (Stream fileStream = File.OpenRead(@"C:\local\path\file.zip"))
using (Stream ftpStream = request.GetRequestStream())
{
    byte[] buffer = new byte[10240];
    int read;
    while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        ftpStream.Write(buffer, 0, read);
        Console.WriteLine("Uploaded {0} bytes", fileStream.Position);
    } 
}

Per lo stato di avanzamento della GUI (WinForms ProgressBar), vedere:
Come possiamo mostrare la barra di avanzamento per il caricamento con FtpWebRequest

Se vuoi caricare tutti i file da una cartella, consulta
Caricamento ricorsivo su server FTP in C # .


Scarica

Il modo più semplice per scaricare un file binario da un server FTP utilizzando .NET framework è utilizzare WebClient.DownloadFile:

WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.DownloadFile(
    "ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");

Se hai bisogno di un controllo maggiore, che WebClientnon offre (come la crittografia TLS / SSL , ecc.), Usa FtpWebRequest. Il modo più semplice è copiare un flusso di risposta FTP FileStreamutilizzando Stream.CopyTo:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    ftpStream.CopyTo(fileStream);
}

Se è necessario monitorare l'avanzamento di un download, è necessario copiare i contenuti in blocchi da soli:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    byte[] buffer = new byte[10240];
    int read;
    while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        fileStream.Write(buffer, 0, read);
        Console.WriteLine("Downloaded {0} bytes", fileStream.Position);
    }
}

Per lo stato di avanzamento della GUI (WinForms ProgressBar), vedere:
Download FTP di FtpWebRequest con ProgressBar

Se si desidera scaricare tutti i file da una cartella remota, vedere
C # Scaricare tutti i file e le sottodirectory tramite FTP .