1

I am downloading a file from FTP using this code:

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(downloadPath);
request.UsePassive = false;
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(_ftpUser, _ftpPass);
using (var response = (FtpWebResponse)request.GetResponse())
using (var responseStream = response.GetResponseStream())
using (var writer = new FileStream(savePath, 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);
    }

}

It works but the file is large and when I download the file with Filezilla client it is much much faster.

Is this to do with the buffer size? What ways can I make this faster?

Guerrilla
  • 13,375
  • 31
  • 109
  • 210
  • 4
    Why are you using only a 2KB buffer? That was suitable 20 years ago, when computers didn't have more than 640KB of RAM installed. – Ken White Jun 19 '19 at 19:40
  • 1
    Could you give me an idea of how I should scale buffer to ram? I took this from an example and wasn't sure how it would effect things so didn't change it – Guerrilla Jun 19 '19 at 19:42
  • 1
    I would double it, test it, double it, test it, etc. until you find an optimal size for your environment (stop when you stop seeing noticeable improvements but do not go into the hundreds of megabytes either) – Igor Jun 19 '19 at 19:45
  • 1
    Or do not even use any explicit buffer. Use `CopyTo` method or even `WebClient.DownloadFile` and let the framework do it for you: https://stackoverflow.com/q/44606028/850848#44608535 – Martin Prikryl Jun 19 '19 at 19:52
  • What @MartinPrikryl said. If you insist on doing it yourself, start by increasing it to 16384. Change `int bufferSize = 16384;`. While you're changing that, get rid of the other 2048 and change `new byte[2048]` to `new byte[bufferSize];` That increases from a 2K buffer to a 16K buffer. You can see if that helps. If it does, try doubling it again to 32768. Repeat until it either stops working or you stop noticing a speed increase. – Ken White Jun 19 '19 at 19:54

0 Answers0