通过SSL访问FTP服务器上的目录时发生FTP错误



我在C#.Net 4.5中开发了一个web服务,它连接到ftp服务器(使用SSL(,并列出存储在ftp服务器目录中的所有文件。该代码去年(2019年初或2018年底(运行良好,但由于我在3周前再次测试了该代码,它不再运行。我尝试过很多东西:

-我已经将目标框架从4.5更改为4.8(文章链接(

-使用fluentFTP nuget包(但我有相同的错误

问题是,我可以使用Filezilla连接到ftp服务器并访问目录,而不会出现任何错误(所以我想这不是防火墙问题(我已经检查了我的计算机和ftp服务器之间的ftp交换日志,在ftp命令MLSD->打开"目录"目录列表的数据通道期间发生错误(来自服务器的最后一条消息->.Net错误:"由于远程方关闭了传输流,身份验证失败">

这是代码:

FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://urlFtpServer:21/directory");
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.EnableSsl = true;
// Sets the user login and password.  
request.Credentials = new NetworkCredential("login", "password");
request.KeepAlive = true;
try
{
// Send the request.
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
IEnumerable<string> lstDirectoryFiles = reader.ReadToEnd()
.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
// Use the user criteria to get only the file needed.
if (string.IsNullOrEmpty(in_searchPattern))
return lstDirectoryFiles.ToList();
Regex rgx = new Regex(in_searchPattern);
return lstDirectoryFiles.Where(st => rgx.IsMatch(st)).ToList();
}
}
}
}
catch (Exception ex)
{
//Here is the exception: authentication failed because the remote party has closed the transport stream
}

请帮助:(

我忘了提到ftp请求方法WebRequestMethods.ftp.MakeDirectory工作得很好

这可能是由于FTP服务器的TLS支持。

尝试将ServicePointManager.SecurityProtocol设置为TLS的不同变体。

这篇文章可能也有帮助。

这主要是由于应用程序的默认安全协议类型设置过低所致。

通过添加此行,在应用程序中设置SecurityProtocol。

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

这可以在调用FTP之前添加,也可以在应用程序启动方法中添加。

最新更新