技术文摘
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#项目中轻松实现文件的上传、下载以及获取文件列表的功能,满足不同的业务需求。
- 太一星晨专区 | 51CTO.com:从负载均衡到应用交付 持续领航高性能ADC技术
- 依据想要的生活来选择第一门编程语言的方法
- Python开发指南之最佳实践精选
- 锐捷网络数据中心核心交换机:超越边界 洞见未来_51CTO.COM
- 东华云管理系统全方位支持云数据中心业务运营与服务 - 51CTO.com
- 京东11.11商品搜索系统架构设计揭秘
- ASP.NET 5 开发者的五重阶段
- Python 语言计数方法的发展历程
- 25个免费资源,助力JavaScript新手程序员
- Github 系统内部所采用的开源软件有哪些?
- 微软推出表情包黑科技 我为尔康少爷试用
- 淘宝应对双11的技术架构剖析
- 7款独具个性的jQuery/HTML5地图插件
- 京东唐志雄谈白条资产证券化的技术视角
- 提升 Java 中锁性能的方法