You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# 使用FtpWebRequest下载FTP服务器ZIP文件内容为空问题求助

FTP下载ZIP文件为空问题解决方案
  • 显式指定二进制传输模式
    ZIP属于二进制文件,未指定传输模式时部分FTP服务器会默认使用ASCII模式传输,会自动转义二进制内容中的换行符,导致文件损坏甚至为空,在创建FtpWebRequest实例后添加如下配置:
requestFileDownload.UseBinary = true;
  • 修正本地路径拼接逻辑
    当前直接拼接字符串的方式容易出现目录分隔符缺失的问题,例如保存目录为D:\download、文件名为test.zip时,拼接结果会变成错误的D:\downloadtest.zip,使用.NET内置的路径拼接方法更稳妥:
string localSavePath = Path.Combine(ary_connect[4], ary_connect[3]);
using (FileStream output = new FileStream(localSavePath, FileMode.Create))
  • 增加内容长度校验和缓冲区刷新
    可以先读取FTP响应的内容长度,提前判断服务器返回的文件是否为空;写入完成后显式刷新文件流缓冲区,避免内容遗留在内存未写入磁盘。

完整修改后的代码如下:

Console.WriteLine("downloading file . . . " + ary_connect[3]);

FtpWebRequest requestFileDownload = (FtpWebRequest)WebRequest.Create(ary_connect[0]);
requestFileDownload.Credentials = new NetworkCredential(ary_connect[1], ary_connect[2]);
requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile;
// 新增:指定二进制传输模式
requestFileDownload.UseBinary = true;
FtpWebResponse responseFileDownload = (FtpWebResponse)requestFileDownload.GetResponse();

// 新增:校验服务器返回的文件大小,值为-1或0时说明服务器端文件为空或路径错误
Console.WriteLine("File size from FTP server: " + responseFileDownload.ContentLength);
            
byte[] buffer = new byte[32768];
using (Stream input = responseFileDownload.GetResponseStream())
{
    // 修改:使用Path.Combine拼接路径
    string savePath = Path.Combine(ary_connect[4], ary_connect[3]);
    using (FileStream output = new FileStream(savePath, FileMode.Create))
    {
        int bytesRead;
        while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write(buffer, 0, bytesRead);
        }
        // 新增:显式刷新缓冲区
        output.Flush();
    }
}
responseFileDownload.Close();
  • 其他排查点
    如果修改后仍有问题,先确认ary_connect[0]对应的FTP文件路径是否正确,直接用FTP客户端工具访问该路径下载文件,确认服务器上的源文件本身不是空文件。

内容的提问来源于stack exchange,提问作者thatDude

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 04:24:03