Access a static resource in CS Code in ASP.NET Razor pages

In an ASP.NET Core Razor Pages application, if you want to access a static file path (like a file in wwwroot) from a .cs file (C# code) — you typically need the absolute file system path to that static file.

Here’s how to do it properly:

Step-by-Step: Access Static File Path in Code-Behind or Service

  1. Inject IWebHostEnvironment

This service provides access to WebRootPath, which points to wwwroot.

Example in Razor Page Code-Behind:

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

public class MyPageModel : PageModel
{
    private readonly IWebHostEnvironment _env;

    public MyPageModel(IWebHostEnvironment env)
    {
        _env = env;
    }

    public void OnGet()
    {
        // files is a folder in wwwroot folder.
        string filePath = Path.Combine(_env.WebRootPath, "files", "example.txt"); 
        // Now you can use filePath to read or write the static file
    }
}

If You’re in a Service (not a Razor Page)

Just Inject the IWebHostEnvironment in the constructor:

public class MyService
{
    private readonly IWebHostEnvironment _env;

    public MyService(IWebHostEnvironment env)
    {
        _env = env;
    }

    public string GetStaticFilePath(string filename)
    {
        return Path.Combine(_env.WebRootPath, "downloads", filename);
    }
}

WebRoot vs ContentRoot

  • env.WebRootPath → points to wwwroot/
  • env.ContentRootPath → points to the base of the project (useful if your file is not in wwwroot), but in the project itself.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *