2

Wondering whether this is possible to read at runtime a json / xml file containing loads of constants (independent of whether this is working in development / production) in a project which is not the main project in an ASP.NET Core solution?

I am not considering moving everything to the appsettings.json and I don't wanna convert everything in a giant piece of class.

Obvisouly at runtime if I am running that line:

var configurationContent = File.ReadAllText(ConfigurationFileName);

while the configuration file is located in the non-main project, the process is going to look for that file in the main project directory.

How can I fix that?

alsami
  • 8,996
  • 3
  • 25
  • 36
Natalie Perret
  • 8,013
  • 12
  • 66
  • 129
  • Please rephrase your title, its misleading. It should be noted that it's about the configuration json files (current one suggest reading arbitrary json files). Also please don't stuff question title with tags, that's what the tag section is for. Have a read on [What are tags, and how should I use them?](https://stackoverflow.com/help/tagging) – Tseng Aug 01 '18 at 07:51

1 Answers1

1

Edit: In general you could configure options that can be injected as IOptions<MyConfiguredOption>. This is the preferred way of doing. In your configureservice method

services.Configure<MyConfiguredOption>(options => Configuration.GetSection("MyConfiguredOption").Bind(options));

Old Answer: What you can do is make sure that the appsettingsfile (or whatever file you want) is copied to the output directory. Right click on it > Properties > Copy to Output directory always.

Adjust the webhostbuilder and set the basedirectory to it

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseKestrel()
            .UseContentRoot(AppContext.BaseDirectory) // <--- this line
            .UseStartup<Startup>();

Files now will always be located in the output directory of the runable application and therefor accessible for every assembly it has a reference to.

Now when you want to load the file content do it like that

var configurationContent = File.ReadAllText(Path.Combine(AppContext.BaseDirectory, ConfigurationFileName));

Though this would work you could just register the configuration and inject IConfiguration to access appsettings instead.

services.AddSingleton(typeof(IConfiguration), Configuration);

This is also not the preferred way.

alsami
  • 8,996
  • 3
  • 25
  • 36