技术文摘
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#项目中轻松实现文件的上传、下载以及获取文件列表的功能,满足不同的业务需求。
- 用字符串中的数字对Python列表排序的方法
- Python中对包含汉字和阿拉伯数字的字符串排序方法
- Odoo实施:成功实施的关键步骤
- 聊天室无法访问,代码无误却连不上,为何?
- Minio Python SDK能否操作Aliyun OSS
- 查看MacBook Pro的Apple Silicon GPU核心数方法
- Go聊天室代码无报错但无法访问的原因
- Go 与 Rust 如何突破 Python GIL 限制以提升程序性能
- Go语言接口实现报错原因及类型名称与方法签名拼写错误的解决办法
- 用torch.onnx.export导出的ONNX模型怎样进行预测
- 利用Go或Rust突破Python GIL限制实现真正并行执行的方法
- Goland频繁提示Unresolved reference的解决方法
- Go或Rust调用Python脚本能否绕过GIL限制实现并行执行
- Goland函数定义遇未解析引用问题的解决方法
- 简易聊天室无法访问且端口被占用的解决方法