ASP.NET Core 使用 FileStream 将 FileResult 文件发送到浏览器后删除该文件

FileStream 在向浏览器发送文件时节省了服务器内存和资源,但如果需要删除文件怎么办?本文介绍如何在发送文件后删除文件;用 C# 编写。

另请参阅:位图创建和下载

使用FileStream向浏览器发送数据效率更高,因为文件是从驱动器复制到浏览器,而不是将其加载到服务器的内存中,然后复制到客户端。但如果文件下载到浏览器后需要删除怎么办?关键是"重写"类Dispose()的方法FileStream。

此代码与.NET Core 3.1、.NET 5、.NET 6、.NET 7 和.NET 8兼容。

以下是从基本 Web 应用程序修改后的 HomeController.cs 文件:

// HomeController.cs

using Microsoft.AspNetCore.Mvc;

namespace WebApplication1.Controllers

{

internal class FileStreamDelete : FileStream

{

readonly string path;

public FileStreamDelete(string path, FileMode mode) : base(path, mode) // NOTE: must create all the constructors needed first

{

this.path = path;

}

protected override void Dispose(bool disposing) // NOTE: override the Dispose() method to delete the file after all is said and done

{

base.Dispose(disposing);

if (disposing)

{

if (System.IO.File.Exists(path))

System.IO.File.Delete(path);

}

}

}

public class HomeController : Controller

{

public async Task<IActionResult> Index(CancellationToken cancel)

{

// NOTE: the file that will be created, sent to the browser and then permanently deleted

string filename = "temp.txt"; // NOTE: use System.Guid.NewGuid() to generate a unique file name

// NOTE: create the text file

await System.IO.File.AppendAllTextAsync(filename, "THIS IS A TEST. THIS IS A TEST. THIS IS A TEST. THIS IS A TEST. THIS IS A TEST. THIS IS A TEST. THIS IS A TEST. THIS IS A TEST. THIS IS A TEST. THIS IS A TEST. THIS IS A TEST. THIS IS A TEST. THIS IS A TEST. THIS IS A TEST.", cancel);

// NOTE: send the text file to the browser and watch it be deleted upon completion of the copy operation

return File(new FileStreamDelete(filename, FileMode.Open), System.Net.Mime.MediaTypeNames.Text.Plain, "downloaded-file.txt");

}

}

}

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

相关推荐
weixin_421994786 小时前
基于 .NET 9.0 的高性能轻量级令牌桶限流服务
.net·.netcore·令牌桶
铁甲前沿7 小时前
一个月玩转MQTT(篇五:开发自己的MQTT WEB页面)
前端·mqtt·asp.net·mqtt web开发
weixin_4219947810 小时前
MVC 模式初探
mvc·.net·.netcore
weixin_421994782 天前
互联网与 Web 应用简介
.net·.netcore
weixin_421994782 天前
依赖注入与中间件 - ASP.NET Core 核心概念
后端·中间件·asp.net
鱼是一只鱼啊3 天前
ASP.NET Core 集成腾讯云 COS 实现文件上传下载完整指南
云计算·asp.net·腾讯云·文件上传·cos
全栈小54 天前
【C#】合理使用DeepSeek相关AI应用为我们提供强有力的开发工具,在.net core 6.0框架下使用JsonNode动态解析json字符串,如何正确使用单问号和双问号做好空值处理
人工智能·c#·json·.netcore·deepseek
时光追逐者5 天前
C#/.NET/.NET Core优秀项目和框架2026年1月简报
c#·.net·.netcore
大尚来也7 天前
双库协同,各取所长:.NET Core 中 PostgreSQL 与 SQLite 的优雅融合实战
postgresql·sqlite·.netcore
无风听海7 天前
.NET10之ASP.NET Core的Filter管线
java·asp.net·.net