技术文摘
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#项目中轻松实现文件的上传、下载以及获取文件列表的功能,满足不同的业务需求。
- Hibernate树形结构详细解析
- Hibernate Extensions剖析
- 10款浏览器Web应用开发性能对比
- 浅论Hibernate outer-join参数
- Spring MVC总结:巧用注解,轻松生活
- 面向对象设计的单一职责原则
- Hibernate配置Proxool简单介绍
- Hibernate Iterator方法介绍
- Hibernate批量操作简述
- Hibernate Session缓存经验梳理
- Python快速搭建HTTP服务
- Scala讲座之函数式编程处理树结构数据
- Hibernate ClassValidator实例讲解
- Hibernate HQL优化笔记
- Scala讲座之面向对象与函数式特点总结