技术文摘
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#项目中轻松实现文件的上传、下载以及获取文件列表的功能,满足不同的业务需求。
- MySQL数据库如何开展地理空间数据分析
- MySQL与PostgreSQL:中小型企业适用的数据库解决方案
- MySQL 中用 LENGTH 函数获取字符串长度的方法
- MySQL与MongoDB:高可用性决策策略探讨
- MySQL与TiDB查询性能对比剖析
- MySQL与TiDB:数据一致性及异步复制对比
- MySQL与PostgreSQL:哪个更契合您的数据库需求
- MySQL与TiDB分布式事务处理能力大比拼
- 怎样借助MTR开展MySQL数据库容量性能测试
- MySQL与PostgreSQL的数据库复制及故障恢复技巧
- MySQL与TiDB高可用性对比剖析
- MySQL与MongoDB:哪个更适配Web应用
- MySQL与Oracle,哪个数据库管理系统更优?
- MySQL与MongoDB:谁更适合内存数据存储
- MySQL与Oracle在空间数据处理及地理信息系统支持方面的对比