0

I am downloading a file from my FTP Server. When it gets to the last bytes it freezes and times out. I had to set the timeout to -1 so it won't time out but the last bytes never finish.

Any ideas?

      FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://xxx" + "/" + fileDownload);
            request.Credentials = new NetworkCredential("xxx", "xxx");
            request.UseBinary = true;
            request.KeepAlive = true;

            request.Timeout = -1;
            request.Method = WebRequestMethods.Ftp.DownloadFile;
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();

            Stream responseStream = response.GetResponseStream();
            FileStream writer = File.Create(@"c:\temp\" + Path.GetFileNameWithoutExtension(fileDownload) + ".csv");


            long length = response.ContentLength;
            int bufferSize = 2048;
            int readCount;
            byte[] buffer = new byte[2048];

           // readCount = responseStream.Read(buffer, 0, bufferSize);

            while (responseStream.CanRead)
            {
                readCount = responseStream.Read(buffer, 0, bufferSize);
                writer.Write(buffer, 0, readCount);

            }     
            responseStream.Close();
            response.Close();

            writer.Close();
Andre DeMattia
  • 631
  • 9
  • 23

1 Answers1

0

CanRead does not do what you think it does. It just indicates whether a stream can in fact be read from at all. Not whether there are any remaining bytes. Instead rewrite your loop like this:

for (int readCount; (readCount = responseStream.Read(buffer, 0, bufferSize)) > 0;) 
{ 
    writer.Write(buffer, 0, readCount); 
}
Kirk Woll
  • 76,112
  • 22
  • 180
  • 195