-2

I want to access values from appsetting.json file, my problem is also that I have in my project multiple appsetting files, not allowed to rename it, how can I solve that problem? Maybe solve with relative path?

want to access from tst -> src/Api/.../appsettings.json Properties appsettings.json Thanks!

  • 1
    1) There is no "appsetting.json". It's "appsettings.json" (plural, with an "s"). 2) It's just a Json-format text file. I'd consider installing [Json.net](https://www.newtonsoft.com/json/help/html/Samples.htm) from Nuget. – paulsm4 May 19 '22 at 15:25
  • Please show us what you have tried and what isn't working for you. – CyanCoding May 19 '22 at 20:24

2 Answers2

1

.net core

var builder = new ConfigurationBuilder()
              .AddJsonFile(@"<path to appsettings.json>");

var configuration = builder.Build();
//  configuration["TAG DESIRED"]

.net framework

 using (var reader = new StreamReader(Directory.GetCurrentDirectory() + "/appsettings.json")) {
        Settings appSettings = JsonConvert.DeserializeObject<Settings>(reader.ReadToEnd());
    }

Settings class must match your json structure

 public class Settings
    {
        .. List of props to be bound.
    }
-5

This worked for me!

var httpDirectory = Path.Combine(new DirectoryInfo(Environment.CurrentDirectory).Parent!.Parent!.Parent!.Parent!.Parent!.FullName,
    "src",
    "ApiGateways",
    "Web.Management",
    "Web.Management.HttpAggregator",
    "bin",
    "Debug",
    "net6.0",
    "appsettings.json"
);
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92