Skip to content

Recommended way to find content root path #53416

@Timovzl

Description

@Timovzl

I have been looking for some documentation on a way to find the content root path that works reliably: in production, from test runners, when running locally from VS, and so on.

By the content root path, I mean the place where we can find files marked with CopyToOutputDirectory. The path should be the directory where the binaries can find their top-level files marked with CopyToOutputDirectory.

All I could find were a lot of StackOverflow posts with non-definitive answers, as well as some semi-related issues on GitHub.

  1. What is the recommended way?

IHostEnvironment.ContentRootPath seems to almost get it right. However, when running from Visual Studio, it points to the source project directory rather than to the bin directory. This keeps it from being the one solution that works reliably.

The simplest solution I have found so far is to manually correct IHostEnvironment.ContentRootPath from Program.cs:

// Fix ContentRootPath for runs from VS
.ConfigureWebHostDefaults(webBuilder =>
{
	webBuilder.UseContentRoot(Path.GetDirectoryName(typeof(Program).Assembly.Location));
	// Snip
}

Still, this is not exactly elegant. Is there a better way? Reliably reaching the content root path seems like a basic requirement.

  1. Would it be useful to document the recommended way?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions