123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- // Create an appsettings.json in the root directory of your console application
- // for example, it should look like:
- // {
- // "Environment": {
- // "Token": "abc-123",
- // "Name": "Production"
- // }
- //}
- //
- // In your Program.cs file, make sure to add:
- // using System.Configuration;
- //
- // And you can use the configuration in your Main function like this:
- //
- // try
- // {
- // var config = new ConfigurationLoader();
- // config.Load();
- // Console.WriteLine(config.GetProperty("Environment.Name"));
- // }
- // catch (Exception e)
- // {
- // Console.WriteLine(e.Message);
- // }
- //
- // This will output "Production", but otherwise it will output a dynamic object
- // (typically a JsonElement since we're using the system.text.json library)
- using System.Text.Json;
- using System.IO;
- namespace System.Configuration
- {
- class ConfigurationLoader
- {
- private dynamic configJsonData;
- public ConfigurationLoader Load(string configFilePath = "appsettings.json")
- {
- var appSettings = File.ReadAllText(configFilePath);
- this.configJsonData = JsonSerializer.Deserialize(appSettings, typeof(object));
- return this;
- }
- public dynamic GetProperty(string key)
- {
- var properties = key.Split(".");
- dynamic property = this.configJsonData;
- foreach (var prop in properties)
- {
- property = property.GetProperty(prop);
- }
- return property;
- }
- }
- }
|