How to delete file after downloading in dotNET Core MVC 6 with C#?

3.9k views Asked by At

I want to delete file just after this is downloaded.

I am using .Net Core MVC 6 C# Controlller.

public IActionResult DownloadPDFReport(string fileName)
        {
            string appBaseUrl = _webHostEnvironment.WebRootPath;

            // concatenating  FileName + FileExtension
            var fileNameToSave = String.Concat(fileName, ".pdf");

            // Combines two strings into a path.
            var filepath = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "pdf_files")).Root + $@"\{fileNameToSave}";

            var verification = _context.Cases.Where(x => x.Id == fileName).FirstOrDefault();
            if (verification == null)
            {
                return NotFound();
            }

            var doc = _context.EAddress_Documents.Where(x => x.CaseID == fileName).FirstOrDefault();

            var reportModel = new ReportViewModel
            {
                CaseID = fileName,
                ReferenceId = verification.Id,
                ApplicantName = "Gopal Sharma",
                Address = verification.Address,
                ClientName = "EXL Services",
                PhoneNumber = "9876543210",
                Latitude = verification.Latitude,
                Longitude = verification.Longitude,
                
                NearbyLocationImageURL = doc.NearbyLocationImage_FilePath
            };

            PdfService.GenerateReport(filepath, reportModel);

            string newFileName = verification.ApplicantName + "_" + DateTime.Now + ".pdf";
            string filePath = "~/pdf_files/" + fileName + ".pdf";
            Response.Headers.Add("Content-Disposition", "inline; filename=" + newFileName + "");
            return File(filePath, "application/pdf");
        }

Any help on this ?

I also tried to make an attribue like below. But this is Old MVC Code. This code does not work in .NET Core MVC 6 C#.

public class DeleteFileAttribute : ActionFilterAttribute
    {
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            filterContext.HttpContext.Response.Flush();
            var filePathResult = filterContext.Result as FilePathResult;
            if (filePathResult != null)
            {
                System.IO.File.Delete(filePathResult.FileName);
            }
        }
    }

enter image description here

Second One--

enter image description here

2

There are 2 answers

3
Mykyta Halchenko On

What I can propose to do is:

  1. You stay the functionality you have as it is and call the method DownloadPDFReport.

  2. After that create an method RemovePDFReport in the same controller with string filePath parameter, something like that:

    public IActionResult RemovePDFReport(string filePath) {
    
       System.IO.File.Delete(filePath);
    
       return Ok();
    
    }
    

3.From client side just call the RemovePDFReport method after DownloadPDFReport and path the built path(you know how to build it on client-side via new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "pdf_files")).Root + $@"\{fileNameToSave}";)

0
GOPAL SHARMA On

After struggling 1 day, I found this solution. Before, I was writing/generating a file at a particular location, then trying to delete that. That way, If I clicked again to download file, It used to throw exception that file is in already in used by some other process.

So now, I found a way in which I don't need to write the file.. Just write your data in stream, then download directly.

Below Is The Simple and Clear Code-

[HttpGet]
        public IActionResult DownloadPDF()
        {
            using (MemoryStream memoryStream = new())
            {
                Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);

                iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, memoryStream);

                pdfDoc.Open();

                PdfPTable headerContentTable = new PdfPTable(1)
                {
                    WidthPercentage = 100f,
                    HorizontalAlignment = Element.ALIGN_CENTER,
                    SpacingBefore = 10f,
                    SpacingAfter = 10f
                };

                headerContentTable.AddCell(new PdfPCell(new Phrase(new Chunk("Employee Address eVerification Report", FontFactory.GetFont(Font.COURIER.ToString(), 16, Font.BOLD, BaseColor.Black)))) { HorizontalAlignment = Element.ALIGN_CENTER, Border = 0, BackgroundColor = BaseColor.Blue, PaddingBottom = 10, PaddingTop = 8 });
                pdfDoc.Add(headerContentTable);

                pdfDoc.Close();
                
                return File(memoryStream.ToArray(), "application/pdf", "Gopal_" + DateTime.Now + ".pdf");
            }
        }