本文介绍了从 FTP 下载文件以及如何提示用户在 ASP.NET C# 中保存/打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当用户单击 ASP.NET C# 页面上的下载按钮时,我想从 FTP 下载文件并在用户的 Web 浏览器中打开下载/保存提示.
I want to download file from FTP and open a download/save prompt in user's web browser, when the user clicks on a download button on ASP.NET C# page.
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: emp" + 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();
推荐答案
@moribvndvs 的回答是正确的.但是使用 WebClient.OpenRead
和 Stream.CopyTo
:
The answer by @moribvndvs is correct. But the code can be way simpler with use of WebClient.OpenRead
and 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
).
(where Response
is ASP.NET HttpResponse
).
另请参阅在 C#/.NET 中向/从 FTP 服务器上传和下载文件.
这篇关于从 FTP 下载文件以及如何提示用户在 ASP.NET C# 中保存/打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!