Skip to content

Instantly share code, notes, and snippets.

@natemcmaster
Last active August 4, 2023 07:59
Show Gist options
  • Save natemcmaster/5556b5662f4a3be63521eca4206ad7fb to your computer and use it in GitHub Desktop.
Save natemcmaster/5556b5662f4a3be63521eca4206ad7fb to your computer and use it in GitHub Desktop.
ContentRoot, WebRoot, BaseDirectory, and CurrentDirectory

Assuming you use template defaults

public static void Main()
{
  var host = new WebHostBuilder()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .Build();
}

public Startup(IHostingEnvironment env)
{
     var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json");
}

During development

- Source/                    <=== Directory.GetCurrentDirectory(), IHostingEnvironment.ContentRootPath
  - MyApp.csproj
  - appsettings.json
  + wwwroot/                 <=== IHostingEnvironment.WebRootPath
  - bin/
    - Debug/
      + netcoreapp2.0/       <=== AppContext.BaseDirectory

After publish

Shell location: $ cd publishDir/

- publishDir/                <=== Directory.GetCurrentDirectory(), IHostingEnvironment.ContentRootPath. AppContext.BaseDirectory
  - MyApp.dll
  - appsettings.json
  + wwwroot/                 <=== IHostingEnvironment.WebRootPath

Why?

During development, you don't need to copy wwwroot to bin/Debug/netcoreapp2.0.

During development, you can change *.js files without needing to restart the server.

After publish, all content unifies to the same directory.

Caveat

This requires launching dotnet MyApp.dll from the correct directory.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment