1 回答
TA贡献1802条经验 获得超5个赞
您实际上并没有告诉 FtpWebRequest 要下载哪个文件,ftpfilename 仅包含 FTP 服务器 URL。尝试修改这一行:
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpfilename));
到:
var requestUri = new Uri(ftpfilename + filename);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(requestUri);
我建议将您的 FtpWebRequest 代码提取到一个带有签名的单独方法中,public byte[] FtpDownloadBinary(Uri fromUri)您可以单独实现和测试该签名,然后您可以将该方法的结果传递到context.Response.BinaryWrite(fileBytes);
==编辑==
以下是 FTP 下载给定二进制 URL 的示例方法:
string username = "anonymous";
string password = "anonymous@example.org";
public byte[] FtpDownloadBinary(Uri fromUri)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(fromUri);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(username, password);
request.UseBinary = true;
request.KeepAlive = true;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
using (var responseStream = response.GetResponseStream())
using (var memoryStream = new MemoryStream())
{
responseStream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
您可以通过使用如下代码将结果保存到系统上的本地文件来测试其是否有效,生成的文件可以使用 7-Zip、WinRAR、WinZip 等打开:
string ftpfilename = "ftp://ftp.ubuntu.com/ubuntu/ls-lR.gz"; //1.7MB example
var requestUri = new Uri(ftpfilename);
var fileBytes = FtpDownloadBinary(requestUri);
using (var fileStream = new FileStream("ls-lR.gz", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
{
fileStream.Write(fileBytes, 0, fileBytes.Length);
}
- 1 回答
- 0 关注
- 169 浏览
添加回答
举报