从 FTP 下载文件以及如何提示用户在 ASP.NET C# 中保

Download file from FTP and how prompt user to save/open file in ASP.NET C#(从 FTP 下载文件以及如何提示用户在 ASP.NET C# 中保存/打开文件)
本文介绍了从 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.OpenReadStream.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# 中保存/打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)