ConfigSectionDemo.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. namespace Apq.Cfg.Samples.Demos;
  2. /// <summary>
  3. /// 示例 3: 配置节 (GetSection) 与子键枚举
  4. /// </summary>
  5. public static class ConfigSectionDemo
  6. {
  7. public static async Task RunAsync(string baseDir)
  8. {
  9. Console.WriteLine("═══════════════════════════════════════════════════════════════");
  10. Console.WriteLine("示例 3: 配置节 (GetSection) 与子键枚举");
  11. Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
  12. var configPath = Path.Combine(baseDir, "section-demo.json");
  13. File.WriteAllText(configPath, """
  14. {
  15. "Database": {
  16. "Primary": {
  17. "Host": "primary.db.local",
  18. "Port": 3306,
  19. "Username": "admin"
  20. },
  21. "Replica": {
  22. "Host": "replica.db.local",
  23. "Port": 3307,
  24. "Username": "reader"
  25. }
  26. },
  27. "Cache": {
  28. "Redis": {
  29. "Host": "redis.local",
  30. "Port": 6379
  31. }
  32. }
  33. }
  34. """);
  35. using var cfg = new CfgBuilder()
  36. .AddJson(configPath, level: 0, writeable: true, isPrimaryWriter: true)
  37. .Build();
  38. // 获取配置节
  39. Console.WriteLine("3.1 使用 GetSection 简化嵌套访问:");
  40. var dbSection = cfg.GetSection("Database");
  41. var primarySection = dbSection.GetSection("Primary");
  42. Console.WriteLine($" Database:Primary:Host = {primarySection.Get("Host")}");
  43. Console.WriteLine($" Database:Primary:Port = {primarySection.Get<int>("Port")}");
  44. // 枚举子键
  45. Console.WriteLine("\n3.2 枚举配置节的子键:");
  46. Console.WriteLine(" Database 的子键:");
  47. foreach (var key in dbSection.GetChildKeys())
  48. {
  49. Console.WriteLine($" - {key}");
  50. }
  51. Console.WriteLine("\n 顶级配置键:");
  52. foreach (var key in cfg.GetChildKeys())
  53. {
  54. Console.WriteLine($" - {key}");
  55. }
  56. // 通过配置节修改值
  57. Console.WriteLine("\n3.3 通过配置节修改值:");
  58. var replicaSection = dbSection.GetSection("Replica");
  59. replicaSection.Set("Port", "3308");
  60. await cfg.SaveAsync();
  61. Console.WriteLine($" 修改后 Database:Replica:Port = {replicaSection.Get("Port")}");
  62. File.Delete(configPath);
  63. Console.WriteLine("\n[示例 3 完成]\n");
  64. }
  65. }