【发布时间】:2020-02-25 09:13:16
【问题描述】:
我在 C# .Net 4.5 中开发了一个 Web 服务,它连接到 ftp 服务器(使用 SSL)并列出存储在 ftp 服务器目录中的所有文件。 该代码去年运行良好(2019 年初或 2018 年底),但由于我在 3 周前再次测试了代码,它不再工作了。 我尝试了很多东西:
-我已将目标框架从4.5更改为4.8(Link of the article)
-使用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 工作正常
【问题讨论】:
-
如果您使用的是 Windows 7,请在创建连接之前设置
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;。您可能还需要验证服务器证书。如果设置SecurityProtocol后也有同样的异常,添加ServicePointManager.ServerCertificateValidationCallback = (s, cert, ch, sec) => { return true; };,进行测试。 -
感谢 Jimi 的回答。我在 Windows 10 上并且已经尝试过:ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;但仍然是完全相同的问题
-
只是为了测试,试试
Ftp.ListDirectoryDetails而不是Ftp.ListDirectory。看看你是否有另一个错误,相同还是继续。如果列表返回空结果(服务器端),则连接可能会丢失(因为它会生成异常,因为 WebRequest 将 HttpStatusCodes > 399 作为异常处理)。从 ftp 地址中删除:21。 -
使用方法 Ftp.ListDirectoryDetails 我有完全相同的错误...当我也从 ftp 地址中删除 :21 (ftpUrl/Directory)...
-
Ftp.ListDirectoryDetails不发送MLSD命令,它发送LIST命令。Ftp.ListDirectory发送NLST命令。
标签: c# ftpwebrequest ftps .net-4.8