C#FTPS FtpWebRequest设置被动模式以使用端口范围

时间:2019-07-02 12:38:41

标签: c# .net ftp ftpwebrequest ftps

我无法使用C#FtpWebRequest连接到特定的FTP。

使用TotalCommander或FileZilla,我可以连接。

有关FTP的信息说:

  • FTPS –隐式SSL / TLS

  • 990端口

  • 无源端口的范围:60000–60100

另一个FTP很好用。

var remoteFile = "ftp://ADDRESS:990/FILE.csv";
var localFile = Server.MapPath("~/tmp/file.csv");

int bufferSize = 2048;

if (!Directory.Exists(Path.GetDirectoryName(localFile)))
    Directory.CreateDirectory(Path.GetDirectoryName(localFile));
/* Create an FTP Request */
FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(remoteFile);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential("USER", "PWD");
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;

ftpRequest.EnableSsl = true;
// Always returns true
ServicePointManager.ServerCertificateValidationCallback = OnValidateCertificate; 

/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
/* Establish Return Communication with the FTP Server */
FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
/* Get the FTP Server's Response Stream */
Stream ftpStream = ftpResponse.GetResponseStream();
/* Open a File Stream to Write the Downloaded File */
FileStream localFileStream = new FileStream(localFile, FileMode.Create);
/* Buffer for the Downloaded Data */
byte[] byteBuffer = new byte[bufferSize];
int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
/* Download the File by Writing the Buffered Data Until the Transfer is Complete */
try
{
    while (bytesRead > 0)
    {
        localFileStream.Write(byteBuffer, 0, bytesRead);
        bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex.ToString());
}
/* Resource Cleanup */
localFileStream.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;

我认为该错误是由于被动端口范围60000-60100引起的。但是我不知道如何设置。

2 个答案:

答案 0 :(得分:1)

FTP被动端口范围是服务器端配置。

您未在 client 端设置被动端口范围– FileZilla或Total Commander也不具有此类配置选项。 FTP客户端使用服务器选择的端口


您的实际问题是.NET / FtpWebRequest不支持隐式 TLS / SSL:
Does .NET FtpWebRequest Support both Implicit (FTPS) and explicit (FTPES)?

答案 1 :(得分:-1)

您将永远无法从 Microsoft 框架连接到隐式 FTPS。它是一个旧的第三方框架,不安全。将客户端更改为显式 FTPS。