Click here to Skip to main content
16,015,583 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to download an Excel file named "Book1.xlsx" from wwwroot folder when I click a Download button.
HTML
<button type="button" class="btn btn-primary" @onclick="DownloadSingleFile">Download</button>

I have tried the below code. But it is showing error - File cannot be used like a method.

What I have tried:

C#
private void DownloadSingleFile()
   {
       var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Book1.xlsx");
       var memory = new MemoryStream();
       if (System.IO.File.Exists(path))
       {
           var net = new System.Net.WebClient();
           var data = net.DownloadData(path);
           var content = new System.IO.MemoryStream(data);
           memory = content;
       }
       memory.Position = 0;
       File(memory.ToArray(), "application/vnd.ms-excel", "Book1.xlsx");
   }

Thanks!
Posted
Updated 19-Oct-23 4:57am
v4

1 solution

I'm assuming, you are working with ASP.NET Core application, to download a file from the wwwroot folder when a button is clicked, you can use the PhysicalFile method and return a FileContentResult from the controller.
Here's an example:
C#
using Microsoft.AspNetCore.Mvc;
using System.IO;
public IActionResult DownloadSingleFile()
{
    var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Book1.xlsx");

    if (System.IO.File.Exists(path))
    {
        var memory = new MemoryStream();
        using (var stream = new FileStream(path, FileMode.Open))
        {
            stream.CopyTo(memory);
        }
        memory.Position = 0;
        return File(memory, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", Path.GetFileName(path));
    }
    else
    {
        return NotFound();
    }
}

This method reads the file from the wwwroot folder, copies it to a memory stream, and then returns it as a file download. The File method is used to return the file content as an application/vnd.openxmlformats-officedocument.spreadsheetml.sheet (MIME type for Excel files) to the client.
Make sure you have configured your routing properly to ensure the DownloadSingleFile method is correctly mapped to the corresponding URL.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900