ConfigurationLoader.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Create an appsettings.json in the root directory of your console application
  2. // for example, it should look like:
  3. // {
  4. // "Environment": {
  5. // "Token": "abc-123",
  6. // "Name": "Production"
  7. // }
  8. //}
  9. //
  10. // In your Program.cs file, make sure to add:
  11. // using System.Configuration;
  12. //
  13. // And you can use the configuration in your Main function like this:
  14. //
  15. // try
  16. // {
  17. // var config = new ConfigurationLoader();
  18. // config.Load();
  19. // Console.WriteLine(config.GetProperty("Environment.Name"));
  20. // }
  21. // catch (Exception e)
  22. // {
  23. // Console.WriteLine(e.Message);
  24. // }
  25. //
  26. // This will output "Production", but otherwise it will output a dynamic object
  27. // (typically a JsonElement since we're using the system.text.json library)
  28. using System.Text.Json;
  29. using System.IO;
  30. namespace System.Configuration
  31. {
  32. class ConfigurationLoader
  33. {
  34. private dynamic configJsonData;
  35. public ConfigurationLoader Load(string configFilePath = "appsettings.json")
  36. {
  37. var appSettings = File.ReadAllText(configFilePath);
  38. this.configJsonData = JsonSerializer.Deserialize(appSettings, typeof(object));
  39. return this;
  40. }
  41. public dynamic GetProperty(string key)
  42. {
  43. var properties = key.Split(".");
  44. dynamic property = this.configJsonData;
  45. foreach (var prop in properties)
  46. {
  47. property = property.GetProperty(prop);
  48. }
  49. return property;
  50. }
  51. }
  52. }