Program.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using Apq.Cfg;
  2. using Apq.Cfg.Yaml;
  3. using Apq.Cfg.Toml;
  4. Console.WriteLine("=== Apq.Cfg 示例 ===\n");
  5. // 创建示例配置文件
  6. var appSettingsPath = Path.Combine(AppContext.BaseDirectory, "appsettings.json");
  7. var localSettingsPath = Path.Combine(AppContext.BaseDirectory, "appsettings.local.json");
  8. // 写入基础配置
  9. File.WriteAllText(appSettingsPath, """
  10. {
  11. "App": {
  12. "Name": "MyApp",
  13. "Version": "1.0.0"
  14. },
  15. "Database": {
  16. "ConnectionString": "Server=localhost;Database=mydb",
  17. "Timeout": 30
  18. },
  19. "Logging": {
  20. "Level": "Information"
  21. }
  22. }
  23. """);
  24. // 写入本地覆盖配置
  25. File.WriteAllText(localSettingsPath, """
  26. {
  27. "Database": {
  28. "ConnectionString": "Server=192.168.1.100;Database=proddb"
  29. },
  30. "Logging": {
  31. "Level": "Debug"
  32. }
  33. }
  34. """);
  35. // 构建配置
  36. var cfg = new CfgBuilder()
  37. .AddJson(appSettingsPath, level: 0, writeable: false)
  38. .AddJson(localSettingsPath, level: 1, writeable: true, isPrimaryWriter: true)
  39. .AddEnvironmentVariables(level: 2, prefix: "APP_")
  40. .Build();
  41. // 读取配置
  42. Console.WriteLine("1. 读取配置值:");
  43. Console.WriteLine($" App:Name = {cfg.Get("App:Name")}");
  44. Console.WriteLine($" App:Version = {cfg.Get("App:Version")}");
  45. Console.WriteLine($" Database:ConnectionString = {cfg.Get("Database:ConnectionString")}");
  46. Console.WriteLine($" Database:Timeout = {cfg.Get<int>("Database:Timeout")}");
  47. Console.WriteLine($" Logging:Level = {cfg.Get("Logging:Level")} (被本地配置覆盖)");
  48. // 检查配置是否存在
  49. Console.WriteLine("\n2. 检查配置是否存在:");
  50. Console.WriteLine($" Exists(App:Name) = {cfg.Exists("App:Name")}");
  51. Console.WriteLine($" Exists(NotExist:Key) = {cfg.Exists("NotExist:Key")}");
  52. // 修改配置
  53. Console.WriteLine("\n3. 修改配置:");
  54. cfg.Set("App:LastRun", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  55. await cfg.SaveAsync();
  56. Console.WriteLine($" 已设置 App:LastRun = {cfg.Get("App:LastRun")}");
  57. // 转换为 Microsoft.Extensions.Configuration
  58. Console.WriteLine("\n4. 转换为 IConfigurationRoot:");
  59. var msConfig = cfg.ToMicrosoftConfiguration();
  60. Console.WriteLine($" msConfig[\"App:Name\"] = {msConfig["App:Name"]}");
  61. // 清理
  62. cfg.Dispose();
  63. File.Delete(appSettingsPath);
  64. File.Delete(localSettingsPath);
  65. Console.WriteLine("\n=== 示例完成 ===");