Home > Blockchain >  C# find file location of xml resource both in web and command line app
C# find file location of xml resource both in web and command line app

Time:11-18

I am building a library in .NET Standard 2.0. I have 1 resource file (xml) that I need to load from disk. The resource file cannot be embedded, the administrator has the liberty to change it after deployment.

The library is shared by a dozen of applications. Some web apps, some winform or command line apps. The resource file is set as "Content" "Always copy" in Visual Studio, so it is always next to my DLL in the bin folder. The library never knows if it is referenced by a command line or web app. But how can I find the location of the resource xml?

Assembly.GetExecutingAssemply().Location: When running from IIS Express, returns some weird temp folder.

Environment.GetCurrentDirectory(): returns C:\Program Files (x86)\IIS Express\

System.Web.Hosting.HostingEnvironment.MapPath("~/bin"): unavailable from within the library.

Any alternative solutions circumventing the problem is also welcome, as long as the admin can change the resource file after deployment.

CodePudding user response:

The AppContext.BaseDirectory property is a good fit for this:

Gets the file path of the base directory that the assembly resolver uses to probe for assemblies.

CodePudding user response:

Inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment

_environment.ContentRootPath
  • Related