articles » current » asp-net-core » delete-file-after-sending-to-the-browser

ASP.NET Core: Delete a FileResult File After Sending It to the Browser Using FileStream

FileStream saves server memory and resources when sending a file to the browser, but what if the file needs to be deleted? This article shows how to delete the file after sending it; written in C#.

See also: Bitmap Creation and Download

It is more efficient to use a FileStream to send data to the browser, because the file is copied from the drive to the browser instead of loading it into the server's memory and then copying to the client. But what if the file needs to be deleted after it is downloaded to the browser? The key is to "override" the Dispose() method of the FileStream class.

Here is the modified HomeController.cs file from a basic web application:


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

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE