1

I'm testing the connection to an FTP server from my c# .NET application which is working. If a connection can be made or the server address is invalid then the response is instant. However, it is very slow if the credentials are valid but no connection can be made. How can I reduce the timeout time on this?

FTP test code:

try
{               
    FtpWebRequest ftpRequest =
        (FtpWebRequest)WebRequest.Create(new Uri("ftp://"+ftpServer+"/"));
    ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
    ftpRequest.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
    ftpRequest.GetResponse();

    MessageBox.Show("OK");
}
catch (Exception ex)
{
    MessageBox.Show("Error");
}

Thanks

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Paul Alexander
  • 2,686
  • 4
  • 33
  • 69

1 Answers1

2

Specify a timeout using FtpWebRequest.Timeout.


Or use an asynchronous request using WebRequest.GetResponseAsync.

Then, you can control, how long you wait for an asynchronous response any way you like.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
  • Be aware that `WebRequest.GetResponseAsync` for `FTP` might cause [issues with getting stuck and never end](https://stackoverflow.com/questions/57307761/c-sharp-program-gets-stuck-in-ftpwebresponse-after-server-disconnects) in some FTP cases. So use sync version `FtpWebRequest.GetResponse` at least for FTP for now. – Dmitry Pavlov Sep 15 '21 at 13:46