C#文件上传、下载与列表相关代码示例

2025-01-02 02:50:10   小编

C#文件上传、下载与列表相关代码示例

在C#开发中,文件的上传、下载以及获取文件列表是常见的操作。本文将为您提供相关的代码示例,帮助您快速实现这些功能。

文件上传

文件上传通常涉及到从客户端将文件传输到服务器端。以下是一个简单的C#文件上传示例:

using System;
using System.IO;
using System.Web;

public partial class FileUploadPage : System.Web.UI.Page
{
    protected void UploadButton_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string fileName = Path.GetFileName(FileUpload1.FileName);
            string filePath = Server.MapPath("~/Uploads/") + fileName;
            FileUpload1.SaveAs(filePath);
            Label1.Text = "文件上传成功!";
        }
        else
        {
            Label1.Text = "请选择要上传的文件!";
        }
    }
}

文件下载

文件下载则是从服务器端将文件发送到客户端。以下是一个实现文件下载的示例代码:

using System;
using System.IO;
using System.Web;

public partial class FileDownloadPage : System.Web.UI.Page
{
    protected void DownloadButton_Click(object sender, EventArgs e)
    {
        string filePath = Server.MapPath("~/Uploads/yourfile.txt");
        FileInfo file = new FileInfo(filePath);
        if (file.Exists)
        {
            Response.Clear();
            Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
            Response.AddHeader("Content-Length", file.Length.ToString());
            Response.ContentType = "application/octet-stream";
            Response.WriteFile(file.FullName);
            Response.End();
        }
        else
        {
            Label1.Text = "文件不存在!";
        }
    }
}

获取文件列表

获取指定目录下的文件列表可以使用以下代码:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string directoryPath = @"C:\YourDirectory";
        string[] fileNames = Directory.GetFiles(directoryPath);
        foreach (string fileName in fileNames)
        {
            Console.WriteLine(fileName);
        }
    }
}

通过以上代码示例,您可以在C#项目中轻松实现文件的上传、下载以及获取文件列表的功能,满足不同的业务需求。

TAGS: C#代码示例 C#文件上传 C#文件下载 C#文件列表

欢迎使用万千站长工具!

Welcome to www.zzTool.com