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");

}

}

}

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

相关推荐
van久6 小时前
.Net Core 学习:DbContextOptions<T> vs DbContextOptions 详细解析
java·学习·.netcore
William_cl7 小时前
【CSDN 专栏】ASP.NET Controller 过滤器详解:ActionFilter(Action 前后逻辑)从入门到避坑
后端·asp.net
询问QQ688238868 小时前
JAVA智能配电房管理系统源码带数据字典及完整文档JAVA智能配电房管理系统源码带数据字典及完整文档
asp.net
靓仔建8 小时前
.net core api在返回json数据时,出现错误,转json不断shi循环。
.netcore
csdn_aspnet8 小时前
C# .NETCore json字符串压缩为一行
c#·json·.netcore
William_cl10 小时前
【CSDN 专栏】ASP.NET Controller 过滤器详解:AuthorizationFilter(权限验证)从入门到避坑
后端·asp.net
van久1 天前
.NET Core 学习第二天:Razor Pages 新建页面及增删改查
学习·.netcore
咖丨喱1 天前
【对端发送的invitation req中channel list和operating channel的operating class不对应】
数据结构·list·asp.net
MoFe11 天前
【.net/.net core】【报错处理】另一个 SqlParameterCollection 中已包含 SqlParameter。
java·.net·.netcore
van久1 天前
.Net Core 学习:LINQ 详解
学习·.netcore·linq