0

I made a simple program download files from my FTP server and usually this works well(I often reboot my laptop if not working and the program runs perfectly) with 0~1 failed trials. However, sometimes the program hangs and nothing happens, and I don't want to reboot my whole PC for that reason. What did I missed and what should I try?

Here is my code:

        while (true)
        {
            try
            {
                ftprequest = (FtpWebRequest)WebRequest.Create(url);
                ftprequest.Credentials = new NetworkCredential(id, pw);
                ftprequest.KeepAlive = false;
                ftprequest.Method = WebRequestMethods.Ftp.DownloadFile;
                ftprequest.UsePassive = false;
                ftprequest.Timeout = 2000;
                using (var resp = ftprequest.GetResponse())
                {
                    resp.Close();
                    break;
                }
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.Timeout && i < 5)
                {
                    i++;
                    Console.WriteLine("Try {0}: failed", i);
                    e.Response.Close();
                }
                else
                {
                    Console.WriteLine("Failed to connect to the server.");
                    Console.ReadKey(true); 
                    return;
                }
            }
        }
  • Are you at the ReadKey() statement? You do not need a While loop. I would set ftprequest at end of code to make sure all paths dispose the object. – jdweng Apr 01 '21 at 15:44
  • [Log file](https://stackoverflow.com/q/9664650/850848) please. + As jdweng wrote, what's the `while (true)` for? + Why `KeepAlive = false`? + Why `UsePassive = false`? – Martin Prikryl Apr 01 '21 at 16:11

1 Answers1

0

Call

ftprequest.Close()

explicitly before

using (var resp = ftprequest.GetResponse())

see https://learn.microsoft.com/en-us/dotnet/api/system.net.ftpwebrequest.getresponse?redirectedfrom=MSDN&view=netframework-4.8#examples

Not Important
  • 762
  • 6
  • 22