Search code examples
c#filepathasp.net-core-3.1

AppContext.BaseDirectory vs Assembly.GetEntryAssembly().Location will be same after publishing the application?


I'm developing ASP.NET Core 3.1 Web API and have my swagger setup. I have added swagger documentation to my project.

  1. Right click API Project -> Build -> Output

enter image description here

  1. This will generate xxx.xml file in my project root folder.

  2. Right click -> xxx.xml -> Copy To Output Directory -> Copy Always

  3. I refer the xxx.xml file in the swagger config in Startup.cs as follows

var xmlCommentsFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlCommentsFullPath = Path.Combine(AppContext.BaseDirectory, xmlCommentsFile);

options.IncludeXmlComments(xmlCommentsFullPath);

Here I should use AppContext.BaseDirectory or Assembly.GetEntryAssembly().Location?

While running this in my local development, I can see this going inside bin\Debug\netcoreapp3.1\ but after publish folder structure will be same?. So correct path will be selected after publish and deploy?


Solution

  • System.AppContext.BaseDirectory should point to the folder that contains the managed entry point assembly, whether that is bin\Debug\netcoreapp3.1\, bin\x64\release\netcoreapp3.1\ or somewhere else.

    You can for example use this property to get the actual location of a single-file executable that gets extracted from one folder and copied into another temp folder before being run.