1. FTP 服务器信息配置:在 Web.config 中存储 FTP 服务器地址、用户名和密码,避免硬编码。
  2. 文件上传:用户选择本地文件,点击上传,通过 FTP 协议上传到服务器。
  3. 文件列表:登录 FTP 服务器后,自动列出服务器上的文件和文件夹。
  4. 文件下载:点击列表中的文件,下载到本地。
  5. 文件夹操作:支持创建新文件夹和删除文件/文件夹。
  6. 友好的用户界面:使用 Bootstrap 快速构建一个美观、响应式的界面,并使用 Alert 组件显示操作结果。

第 1 步:创建 ASP.NET Web 项目

  1. 打开 Visual Studio。
  2. 选择 "创建新项目"。
  3. 选择 "ASP.NET Web 应用程序"。
  4. 选择 "Web Forms" 或 "MVC" 模板均可,这里以 Web Forms 为例。
  5. 给项目命名,FtpWebApp

第 2 步:配置 Web.config

Web.config 文件中添加一个 appSettings 节点,用于存储 FTP 服务器的连接信息,这样做的好处是,当服务器信息变更时,只需修改配置文件,无需重新编译代码。

asp.net的网页ftp上传下载源代码

<configuration>
  <appSettings>
    <!-- FTP 服务器地址,ftp://yourserver.com 或 192.168.1.100 -->
    <add key="FtpServer" value="ftp://yourftpserver.com" />
    <!-- FTP 用户名 -->
    <add key="FtpUserName" value="your_username" />
    <!-- FTP 密码 -->
    <add key="FtpPassword" value="your_password" />
    <!-- FTP 服务器上的初始路径,"/public_html/uploads" -->
    <add key="FtpRootPath" value="/uploads" />
  </appSettings>
  <!-- 其他系统配置... -->
</configuration>

重要提示:请将上述值替换为您自己的 FTP 服务器信息。

asp.net的网页ftp上传下载源代码


第 3 步:创建 FTP 辅助类 (FtpHelper.cs)

为了使代码结构清晰、易于复用,我们创建一个静态的 FtpHelper 类来封装所有 FTP 操作。

在项目中右键 -> 添加 -> 类,命名为 FtpHelper.cs

using System;
using System.IO;
using System.Net;
using System.Collections.Generic;
public static class FtpHelper
{
    // FTP 服务器地址
    private static string GetServerUrl() => System.Configuration.ConfigurationManager.AppSettings["FtpServer"];
    // FTP 用户名
    private static string GetUserName() => System.Configuration.ConfigurationManager.AppSettings["FtpUserName"];
    // FTP 密码
    private static string GetPassword() => System.Configuration.ConfigurationManager.AppSettings["FtpPassword"];
    // FTP 根路径
    private static string GetRootPath() => System.Configuration.ConfigurationManager.AppSettings["FtpRootPath"];
    /// <summary>
    /// 获取 FTP 服务器上的文件和文件夹列表
    /// </summary>
    /// <returns>包含名称、是否为文件夹、大小和修改时间的列表</returns>
    public static List<FtpItem> GetList()
    {
        List<FtpItem> items = new List<FtpItem>();
        string path = GetRootPath();
        try
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(GetServerUrl() + path);
            request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
            request.Credentials = new NetworkCredential(GetUserName(), GetPassword());
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            using (Stream responseStream = response.GetResponseStream())
            using (StreamReader reader = new StreamReader(responseStream))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    // 解析 FTP LIST 命令的输出格式(Unix 格式)
                    // 示例: "drwxr-xr-x   2 user group       4096 Jan 10 12:00 MyFolder"
                    // 示例: "-rw-r--r--   1 user group      1234 Jan 10 12:01 myfile.txt"
                    string[] parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length < 9) continue;
                    string name = string.Join(" ", parts, 8, parts.Length - 8);
                    bool isDirectory = parts[0].StartsWith("d");
                    items.Add(new FtpItem
                    {
                        Name = name,
                        IsDirectory = isDirectory,
                        Size = isDirectory ? 0 : long.Parse(parts[4]),
                        ModifiedDate = $"{parts[5]} {parts[6]}"
                    });
                }
            }
        }
        catch (Exception ex)
        {
            // 在实际应用中,这里应该记录日志
            // throw;
        }
        return items;
    }
    /// <summary>
    /// 上传文件到 FTP 服务器
    /// </summary>
    /// <param name="localFilePath">本地文件完整路径</param>
    /// <param name="remoteFileName">服务器上保存的文件名</param>
    public static void UploadFile(string localFilePath, string remoteFileName)
    {
        string remotePath = GetRootPath() + "/" + remoteFileName;
        try
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(GetServerUrl() + remotePath);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential(GetUserName(), GetPassword());
            using (FileStream fileStream = File.OpenRead(localFilePath))
            using (Stream requestStream = request.GetRequestStream())
            {
                fileStream.CopyTo(requestStream);
            }
        }
        catch (Exception ex)
        {
            // 在实际应用中,这里应该记录日志
            // throw;
        }
    }
    /// <summary>
    /// 从 FTP 服务器下载文件
    /// </summary>
    /// <param name="remoteFileName">服务器上的文件名</param>
    /// <param name="localFilePath">本地保存路径</param>
    public static void DownloadFile(string remoteFileName, string localFilePath)
    {
        string remotePath = GetRootPath() + "/" + remoteFileName;
        try
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(GetServerUrl() + remotePath);
            request.Method = WebRequestMethods.Ftp.DownloadFile;
            request.Credentials = new NetworkCredential(GetUserName(), GetPassword());
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            using (Stream responseStream = response.GetResponseStream())
            using (FileStream fileStream = File.Create(localFilePath))
            {
                responseStream.CopyTo(fileStream);
            }
        }
        catch (Exception ex)
        {
            // 在实际应用中,这里应该记录日志
            // throw;
        }
    }
    /// <summary>
    /// 在 FTP 服务器上创建文件夹
    /// </summary>
    /// <param name="folderName">文件夹名称</param>
    public static void CreateFolder(string folderName)
    {
        string remotePath = GetRootPath() + "/" + folderName;
        try
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(GetServerUrl() + remotePath);
            request.Method = WebRequestMethods.Ftp.MakeDirectory;
            request.Credentials = new NetworkCredential(GetUserName(), GetPassword());
            request.UsePassive = true;
            request.UseBinary = true;
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                // 创建成功后,关闭响应流
                response.Close();
            }
        }
        catch (Exception ex)
        {
            // 文件夹可能已存在,或者其他错误
            // 在实际应用中,这里应该记录日志
            // throw;
        }
    }
    /// <summary>
    /// 删除 FTP 服务器上的文件或文件夹
    /// </summary>
    /// <param name="itemName">要删除的文件或文件夹名称</param>
    public static void DeleteItem(string itemName)
    {
        string remotePath = GetRootPath() + "/" + itemName;
        try
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(GetServerUrl() + remotePath);
            request.Method = WebRequestMethods.Ftp.DeleteFile; // FTP 删除文件和文件夹都使用 DeleteFile 方法
            request.Credentials = new NetworkCredential(GetUserName(), GetPassword());
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                // 删除成功后,关闭响应流
                response.Close();
            }
        }
        catch (Exception ex)
        {
            // 在实际应用中,这里应该记录日志
            // throw;
        }
    }
}
/// <summary>
/// 用于存储 FTP 列表项信息的辅助类
/// </summary>
public class FtpItem
{
    public string Name { get; set; }
    public bool IsDirectory { get; set; }
    public long Size { get; set; }
    public string ModifiedDate { get; set; }
}

asp.net的网页ftp上传下载源代码