使用 FtpWebRequest 减少等待 FTP 连接的时间

Reduce time waiting for FTP connection with FtpWebRequest

我正在测试从正在运行的 c# .NET 应用程序到 FTP 服务器的连接。如果可以建立连接或服务器地址无效,则响应是即时的。但是,如果凭据有效但无法建立连接,则速度非常慢。 如何减少超时时间?

FTP 测试代码:

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");
}

谢谢

使用 FtpWebRequest.Timeout 指定超时。


或者使用异步请求 WebRequest.GetResponseAsync

然后,您可以随意控制等待异步响应的时间。