C# FTP 下载文件并返回浏览器:完整示例和代码
C# FTP 下载文件并返回浏览器:完整示例和代码
本文将介绍如何在 C# 中使用 FTP 下载文件并将其返回给浏览器,并提供完整代码示例和使用说明。
代码示例
using System;
using System.IO;
using System.Net;
using System.Web;
public class FtpDownloader
{
public static void DownloadFile(string ftpUrl, string userName, string password, HttpResponse response)
{
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(userName, password);
using (FtpWebResponse ftpResponse = (FtpWebResponse)request.GetResponse())
using (Stream ftpStream = ftpResponse.GetResponseStream())
{
response.Clear();
response.ContentType = "application/octet-stream";
response.AddHeader("Content-Disposition", "attachment; filename='" + Path.GetFileName(ftpUrl) + "'");
response.BufferOutput = false;
byte[] buffer = new byte[10240]; // 10KB buffer, you can adjust the size as per your requirement
int bytesRead;
while ((bytesRead = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
{
response.OutputStream.Write(buffer, 0, bytesRead);
response.Flush();
}
response.End();
}
}
catch (Exception ex)
{
response.Write("Error: " + ex.Message);
response.End();
}
}
}
使用方法
- 将上述代码添加到您的 C# 项目中。
- 在需要下载文件并返回给浏览器的地方调用
DownloadFile方法。
以下是一个示例:
protected void Page_Load(object sender, EventArgs e)
{
string ftpUrl = "ftp://example.com/file.txt";
string userName = "ftpUsername";
string password = "ftpPassword";
FtpDownloader.DownloadFile(ftpUrl, userName, password, Response);
}
注意
- 请确保将
ftpUrl替换为实际的 FTP 文件 URL,以及将userName和password替换为实际的 FTP 凭据。 - 您可以在
DownloadFile方法中根据需要调整缓冲区大小 (buffer)。
通过以上步骤,您就可以使用 C# 从 FTP 服务器下载文件并将其返回给浏览器了。
原文地址: https://www.cveoy.top/t/topic/qx6l 著作权归作者所有。请勿转载和采集!