Download FTP using C #

6

I'm trying to download an FTP server. The problem is this:

I need a way to partition the file I'm downloading. So that it is downloaded part by part and not complete at once. Doing so asynchronously also does not work for my case because it would also be downloaded all ...

Using the FtpWebRequest and FtpWebResponse classes it is possible to define (in bytes) which part of the file will begin downloading, through the .ContentOffset property of the FtpWebRequest class. Even so, it does not exist, or at least I do not know any property that delimits how much of this file will be downloaded. Here is the code, for illustration, below:

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(endereco);

request.Credentials = new NetworkCredential(usuario, senha);

request.Method = WebRequestMethods.Ftp.DownloadFile;

request.ContentOffset = 5000; //inicia o download desta posicao.

using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
    using (Stream stm = response.GetResponseStream())
    {
        using (FileStream fs = new FileStream(LocalArquivo, FileMode.Create))
        {
            byte[] buffer = new byte[32768];
            while (true)
            {
                int read = stm.Read(buffer, 0, buffer.Length);
                if (read <= 0)
                    return;
                fs.Write(buffer, 0, read);
            }
        }
    }
}

I've also tried using the WebClient class. But I did not succeed either. Through the DownloadProgressChanged event it is possible to obtain the amount of bytes that have already been downloaded through the .BytesReceived property of DownloadProgressChangedEventArgs. Follow the code, for illustration, below:

using (WebClient cliente = new WebClient())
{

  cliente.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);

  cliente.Credentials = new NetworkCredential(usuario, senha);

  Uri url = new Uri(endereco);

  cliente.DownloadFileAsync(url, LocalArquivo);

}

private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {            
        long progresso = e.BytesReceived; //numero de bytes ja baixados...
    }

I would like some tips or instructions on how to perform this download in order not to download the entire file, but rather in parts.

Thank you very much!

    
asked by anonymous 29.10.2015 / 14:40

1 answer

2

Add the AddRange Method to get only part of the file.

request.AddRange(0, 999);

Node code above you will get the first 1000 bytes of the file.

    
23.11.2015 / 22:53