FtpWebRequest.GetRequestStream() - 无法有时连接到远程服务器

时间:2017-04-24 17:41:18

标签: c# asp.net asp.net-web-api ftp ftpwebrequest

我正在尝试将文件上传到第三方FTP服务器。它大部分时间都是成功的,但有时会有一段时间可能会持续几分钟失败。当我调用GetRequestStream()并且消息为Unable to connect to the remote server且没有内部异常或其他信息时,会引发异常。我的请求超时设置为100000,但异常会在20秒左右提升。

我还在请求时记录了FTP服务器的IP地址,我看到相同的IP地址有时会工作,有时无法连接,所以我认为这不是防火墙问题。< / p>

Upload方法用作使用ASP.NET Web API进行API调用的一部分,用户通过此API调用来触发上传。

代码:

try
{
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(hostURI);
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["FTPUser"], ConfigurationManager.AppSettings["FTPPW"]);
    request.EnableSsl = true;
    request.KeepAlive = false;

    byte[] fileContents;
    using (var readStream = System.IO.File.OpenRead(pathToFile))
    {
        fileContents = new byte[readStream.Length];
        readStream.Read(fileContents, 0, fileContents.Length);
        readStream.Close();
    }

    request.ContentLength = fileContents.Length;

    Stream requestStream = request.GetRequestStream();
    requestStream.Write(fileContents, 0, fileContents.Length);
    requestStream.Close();

    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
    response.Close();
}
catch (Exception e)
{
    Debug.WriteLine("Message: " + e.Message + ", Stack Trace: " + e.StackTrace + ", Inner Exception: " + e.InnerException);
}

例外:

  

System.Net.WebException:无法连接到远程服务器       System.Net.FtpWebRequest.GetRequestStream()at       PGServer.Helpers.FTPHelper.Upload(String pathToFile,String ftpFolderName,String newFileName)

1 个答案:

答案 0 :(得分:0)

同样的错误。一年之后,ftp的安全性更高。最近它显示&#34; 无法连接到远程服务器    在System.Net.FtpWebRequest.GetRequestStream()&#34; 在这里我做了什么:  0卸载防病毒软件。 1重新启动ftp in.it工作的计算机

相关问题