Copy and download file when deploying application

This guide demonstrates how to copy and download file when deploying application.

Step by step

1. Create new Blazor application.

2. Add desired file(s) in server folder [APP_NAME].csproj file

<ItemGroup>
    <None Include="ProductSales.pdf" CopyToPublishDirectory="Always" />
    ...

3. Execute custom method to download the file.

MainPage.razor.cs

using System.Threading.Tasks;

namespace SampleBlazor.Pages
{
    public partial class MainPageComponent
    {
        public async Task GetFile(string fileName)
        {
            UriHelper.NavigateTo($"api/custommethod/getfile?fileName={fileName}", true);
        }
    }
}

CustomController.cs

using System.IO;
using Microsoft.AspNetCore.Mvc;

namespace SampleBlazor
{
    [Route("api/[controller]/[action]")]
    public class CustomMethodController : Controller
    {
        [HttpGet]
        public IActionResult GetFile(string fileName)
        {
            if (System.IO.File.Exists(fileName))
            {
                return File(System.IO.File.ReadAllBytes(fileName), contentType: "application/pdf", fileName);
            }
            return NotFound();
        }
    }
}

4. Run the application and download file.

We are here for you

Making our users happy is always a priority for us.