从 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# 中保存/打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Custom Error Queue Name when using EasyNetQ for RabbitMQ?(使用 EasyNetQ for RabbitMQ 时自定义错误队列名称?)
How to generate password_hash for RabbitMQ Management HTTP API(如何为 RabbitMQ 管理 HTTP API 生成密码哈希)
Rabbitmq Ack or Nack, leaving messages on the queue(Rabbitmq Ack 或 Nack,将消息留在队列中)
Wait for a single RabbitMQ message with a timeout(等待一条带有超时的 RabbitMQ 消息)
Setup RabbitMQ consumer in ASP.NET Core application(在 ASP.NET Core 应用程序中设置 RabbitMQ 消费者)
Specify Publish timeouts in mass transit(指定公共交通中的发布超时)