-1

How I can get file path from app.setting to my class. For example, I hard codded the file path on my class like

var x= $"{Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}\mydoc.docx";

But I want to get it from app.setting like

"PluginSettings": { "mypath": ["path to my desktop"

], "mytemplate": ["path to my desktop"] },

so I want my class get the mypath anmytemplate from app.setting. any help

Luuk
  • 12,245
  • 5
  • 22
  • 33
Luay
  • 3
  • 2
  • 2
    You can search for IOptions pattern and dependency injection. Assuming you are using net core or later. – funatparties May 25 '22 at 19:45
  • I used string dbConn2 = configuration.GetSection("PluginSettings").GetSection("templateDocxFilePath").Value; and get error Object reference not set to an instance of an object.' Im using .net6 console application. – Luay May 25 '22 at 20:30
  • I went to different approach This is my appsetting "RoundTheCodeSync": { "Title": "Our Sync Tool", "Interval": "0:30:00", "ConcurrentThreads": 10 }, and I code like var x = _configuration.GetSection("RoundTheCodeSync").GetChildren().FirstOrDefault(config => config.Key == "Title").Value; and still get error Object reference not set to an instance of an object – Luay May 25 '22 at 21:12

2 Answers2

0

You have a bug in your code. GetChildren creates a list of your properties, so you have to find a proper items using where at first. But since it will return a list of items that fits a where condition, you will have to select a first item and after this a value, a path or a key of this item

var title = configuration.GetSection("RoundTheCodeSync")
                         .GetChildren()
                         .FirstOrDefault(c =>c.Key=="Title" )
                         .Value;

but there is a much shorter way, since a section just is a dictionary

 var title = configuration.GetSection("RoundTheCodeSync")["Title"];
Serge
  • 40,935
  • 4
  • 18
  • 45
  • still have same error. – Luay May 26 '22 at 01:10
  • public Program(IConfiguration config) { _config = config; } var applicationSettings = _config.GetSection("RoundTheCodeSync"); and still have same error – Luay May 26 '22 at 01:36
-1

I figure out the simple solution

var appname = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("RoundTheCodeSync")["Title"];

And it's work fine.

Luay
  • 3
  • 2