Read an application content file in ASP.NET Core

ASP.NET Core replaces Server.MapPath with explicit hosting paths and file providers. Use the content-root provider for files that belong to the application, and the web-root provider for public web assets.

Keep private application files outside wwwroot unless they are intentionally public. Resolving a path and authorizing its disclosure are separate operations.

Read a known resource

Create dotnet new web -n ContentDemo -f net10.0. In the project directory, create Data/message.txt containing Hello from a file, then replace Program.cs:

C#
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/message", async (IWebHostEnvironment environment) => {
	var file = environment.ContentRootFileProvider.GetFileInfo("Data/message.txt");
	if (!file.Exists) return Results.NotFound();
	using var reader = new StreamReader(file.CreateReadStream());
	return Results.Text(await reader.ReadToEndAsync());
});
app.Run();

Run the project and request /message. Expect the file's text. Removing the file produces HTTP 404.

Include the file in deployment

Add the following to the project file when the resource must ship with the application:

XML
<ItemGroup>
  <Content Include="Data/message.txt" CopyToOutputDirectory="PreserveNewest"
           CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>

The example uses a fixed path. Do not turn it into an arbitrary file-download endpoint by passing an unchecked request path into filesystem APIs. For editable uploads, choose a separately configured storage root and validate names, authorization and containment. A content root may be read-only in a deployed application.

Official references

File Providers in ASP.NET Core
Learn how ASP.NET Core abstracts file system access through the use of File Providers.
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/file-providers?view=aspnetcore-10.0
ASP.NET Core file providers

Author: Herman Schoenfeld