C#连接FTP服务器下载文件报错求助
解决C# FtpWebRequest连接FTP服务器的被动/主动模式错误
我之前维护旧项目时碰到过类似的FtpWebRequest兼容性问题,结合你描述的情况,咱们一步步拆解问题和解决方案:
先分析两种模式报错的可能原因
- 被动模式(UsePassive=true)报227错误:其实227本身是FTP服务器返回的正常响应,表示已进入被动模式。但FtpWebRequest对某些服务器的响应格式兼容性较差,比如服务器返回的被动IP/端口解析逻辑有问题,或者默认的SSL设置和服务器不兼容(你提到服务器不支持TLS,这点很关键)。
- 主动模式(UsePassive=false)报500错误:要么是你的服务器不支持主动模式的PORT命令格式,要么是你本地网络的防火墙阻止了服务器主动连接你的客户端端口(主动模式需要客户端开放端口给服务器回调),而第三方FTP客户端通常会自动切换到被动模式,所以能正常工作。
针对性解决方案
方案1:修复FtpWebRequest的配置
首先明确禁用SSL(匹配服务器无加密的要求),同时完善异常捕获逻辑,能更清晰看到服务器的真实响应:
using System; using System.IO; using System.Net; class FtpDownloader { public static void Main(string[] args) { FtpWebRequest ftpRequest = null; FtpWebResponse ftpResponse = null; try { ftpRequest = (FtpWebRequest)FtpWebRequest.Create("ftp://ftp.autoherosrpg.com/hash.xml"); ftpRequest.Credentials = new NetworkCredential("game@autoherosrpg.com", "*********"); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = false; ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; // 明确禁用SSL,避免和服务器的无加密要求冲突 ftpRequest.EnableSsl = false; ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); Console.WriteLine($"服务器响应状态: {ftpResponse.StatusDescription}"); // 读取响应流并保存文件 using (Stream responseStream = ftpResponse.GetResponseStream()) using (FileStream fileStream = new FileStream("hash.xml", FileMode.Create)) { responseStream.CopyTo(fileStream); Console.WriteLine("文件下载完成"); } } catch (WebException ex) { // 捕获FTP专属响应,获取更详细的错误信息 if (ex.Response is FtpWebResponse ftpExResp) { Console.WriteLine($"FTP错误代码: {ftpExResp.StatusCode}"); Console.WriteLine($"服务器详细描述: {ftpExResp.StatusDescription}"); } Console.WriteLine($"异常信息: {ex.Message}"); } finally { // 确保资源释放 ftpResponse?.Close(); ftpRequest?.Abort(); } } }
方案2:改用第三方FTP库(推荐)
FtpWebRequest已经被.NET官方标记为过时(.NET Core/.NET 5+中不再推荐使用),兼容性问题较多。推荐使用FluentFTP,它对各种FTP服务器的兼容性更好,代码也更简洁:
- 先通过NuGet安装FluentFTP:
Install-Package FluentFTP - 编写下载代码:
using System; using FluentFTP; class FtpDownloader { public static void Main(string[] args) { // 初始化FTP客户端 using (var ftpClient = new FtpClient("ftp.autoherosrpg.com", "game@autoherosrpg.com", "*********")) { try { ftpClient.EnableSsl = false; // 禁用SSL匹配服务器设置 ftpClient.Connect(); // 建立连接 Console.WriteLine("成功连接到FTP服务器"); // 下载文件:本地路径 -> 服务器路径 ftpClient.DownloadFile("./hash.xml", "/hash.xml"); Console.WriteLine("文件下载完成"); ftpClient.Disconnect(); } catch (Exception ex) { Console.WriteLine($"下载失败: {ex.Message}"); } } } }
这个库会自动处理被动模式的响应解析,基本不会出现FtpWebRequest的兼容性问题,而且API更直观。
内容的提问来源于stack exchange,提问作者MikeJ
相关产品推荐
相关产品推荐

