从FTP下载文件以及如何提示用户在 ASP.NET C#中保存/打开文件
本文关键字:文件 NET ASP 保存 用户 提示 下载 FTP 何提示 | 更新日期: 2023-09-27 18:37:22
当用户单击C#页面上的下载按钮时,我想从FTP下载文件并在用户的Web浏览器中打开下载/保存提示 ASP.NET。
string strDownloadURL = System.Configuration.ConfigurationSettings.AppSettings["DownloadURL"];
string HostName = System.Configuration.ConfigurationSettings.AppSettings["HostName"];
string strUser = System.Configuration.ConfigurationSettings.AppSettings["BasicAuthenticationUser"];
string strPWD = System.Configuration.ConfigurationSettings.AppSettings["BasicAuthenticationPWD"];
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(HostName + strFile);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(strUser, strPWD);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
string fileName = @"c:'temp'" + strFile + "";
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
FileStream file = File.Create(fileName);
byte[] buffer = new byte[2 * 1024];
int read;
while ((read = responseStream.Read(buffer, 0, buffer.Length)) > 0) { file.Write(buffer, 0, read); }
file.Close();
responseStream.Close();
response.Close();
因此,假设您要将 FTP 请求的响应流向下写入 ASP.NET 响应流,并希望在浏览器中触发下载对话框,则需要在响应中设置 Content-Disposition
标头。
// note: since you are writing directly to client, I removed the `file` stream
// in your original code since we don't need to store the file locally...
// or so I am assuming
Response.AddHeader("content-disposition", "attachment;filename=" + strFile);
byte[] buffer = new byte[2 * 1024];
int read;
while ((read = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
Response.OutputStream.Write(buffer, 0, read);
}
responseStream.Close();
response.Close();
@moribvndvs的答案是正确的。但是使用WebClient.OpenRead
和Stream.CopyTo
代码可以更简单:
var filename = "file.zip";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
var client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
var url = "ftp://ftp.example.com/remote/path/" + filename;
using (var ftpStream = client.OpenRead(url))
{
ftpStream.CopyTo(Response.OutputStream);
}
(其中Response
是 ASP.NET HttpResponse
)。
另请参阅在 C#/.NET 中将文件上载和下载到 FTP 服务器/从 FTP 服务器下载文件。