HttpPostedFile
类和
System.IO
命名空间中的相关方法来实现。以下是一个简单的示例代码:“
csharp,// 文件上传,if (fileUploadControl.HasFile),{, string filePath = Server.MapPath("~/Uploads/") + fileUploadControl.FileName;, fileUploadControl.SaveAs(filePath);,}// 文件删除,string filePath = Server.MapPath("~/Uploads/") + "filename.ext";,if (System.IO.File.Exists(filePath)),{, System.IO.File.Delete(filePath);,},
“
在ASP.NET中,文件上传和文件删除是常见的功能需求,以下是关于这两个功能的详细代码实现:
文件上传
# 1. 使用FileUpload控件(ASP.NET WebForms)
前台代码(aspx):
“`asp
<%@ %="" language="C#" page="">
“`
后台代码(aspx.cs):
“`csharp
using System;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : Page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// 检查上传目录是否存在,不存在则创建
string uploadPath = Server.MapPath(“~/UploadFiles/”);
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
}
}
protected void UploadButton_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
try
{
string fileName = Path.GetFileName(FileUploadControl.PostedFile.FileName);
string fileExtension = Path.GetExtension(fileName);
string allowedExtensions = “.txt,.jpg,.png,.doc,.docx”; // 允许上传的文件类型
if (allowedExtensions.Contains(fileExtension))
{
string uploadPath = Server.MapPath(“~/UploadFiles/”) + fileName;
FileUploadControl.SaveAs(uploadPath);
StatusLabel.Text = “文件上传成功!”;
}
else
{
StatusLabel.Text = “不允许的文件类型。”;
}
}
catch (Exception ex)
{
StatusLabel.Text = “上传失败:” + ex.Message;
}
}
else
{
StatusLabel.Text = “请选择要上传的文件。”;
}
}
“`
# 2. 使用IFormFile接口(ASP.NET Core MVC或Razor Pages)
前台代码(Razor Pages,如Upload.cshtml):
“`html
@page
@model YourNamespace.Pages.UploadModel
@{
ViewData[“Title”] = “文件上传”;
@if (Model.UploadedFileName != null)
文件上传成功:@Model.UploadedFileName
“`
后台代码(Upload.cshtml.cs):
“`csharp
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace YourNamespace.Pages
public class UploadModel : PageModel
{
[BindProperty]
public IFormFile File { get; set; }
public string UploadedFileName { get; private set; }
public void OnPost()
{
if (File != null && File.Length > 0)
{
var filePath = Path.Combine(Directory.GetCurrentDirectory(), “wwwroot”, “uploads”, File.FileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
File.CopyTo(stream);
}
UploadedFileName = File.FileName;
}
}
}
“`
文件删除
# 使用File类的Delete方法(适用于ASP.NET WebForms和ASP.NET Core)
示例代码:
“`csharp
string filePath = Server.MapPath(“~/UploadFiles/example.txt”); // 替换为要删除的文件路径
if (File.Exists(filePath))
File.Delete(filePath);
// 可以添加日志记录或其他操作,表示文件已删除
else
// 处理文件不存在的情况
“`
在ASP.NET中,文件上传和删除通常涉及对服务器文件系统的直接操作,对于文件上传,可以使用`FileUpload`控件(在ASP.NET WebForms中)或`IFormFile`接口(在ASP.NET Core中)来接收用户选择的文件,并将其保存到服务器上的指定目录,对于文件删除,可以使用`System.IO.File`类的`Delete`方法来删除指定的文件,在实际应用中,还需要考虑安全性、性能和错误处理等方面的问题。