SharedConfigStore.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System.IO;
  2. using System.Xml.Linq;
  3. namespace ivf_tl_Operate.Helpers
  4. {
  5. /// <summary>
  6. /// 配置收敛:operate↔control 共享连接键的唯一数据源文件(tl-shared.config)读写。
  7. /// 文件格式 = 独立 appSettings 片段(&lt;appSettings&gt;&lt;add key.. value../&gt;&lt;/appSettings&gt;),
  8. /// 正是 &lt;appSettings file="…"&gt; 期望的外部文件格式 → 两进程经 file= 只读合并即读到。
  9. /// 用 XDocument 直写,绕开 ConfigurationManager 写回 file= 的不确定行为。
  10. /// </summary>
  11. public static class SharedConfigStore
  12. {
  13. /// <summary>读片段文件里某键值;文件不存在或键缺失返回 null。</summary>
  14. public static string Read(string path, string key)
  15. {
  16. if (!File.Exists(path)) return null;
  17. try
  18. {
  19. var doc = XDocument.Load(path);
  20. foreach (var add in doc.Descendants("add"))
  21. {
  22. if ((string)add.Attribute("key") == key)
  23. return (string)add.Attribute("value");
  24. }
  25. return null;
  26. }
  27. catch
  28. {
  29. return null;
  30. }
  31. }
  32. /// <summary>写某键值(存在则更新,不存在则新增);文件不存在则创建片段骨架。</summary>
  33. public static void Write(string path, string key, string value)
  34. {
  35. XDocument doc;
  36. if (File.Exists(path))
  37. {
  38. try { doc = XDocument.Load(path); }
  39. catch { doc = NewDoc(); }
  40. }
  41. else
  42. {
  43. doc = NewDoc();
  44. }
  45. var root = doc.Root ?? new XElement("appSettings");
  46. if (doc.Root == null) doc.Add(root);
  47. XElement target = null;
  48. foreach (var add in root.Elements("add"))
  49. {
  50. if ((string)add.Attribute("key") == key) { target = add; break; }
  51. }
  52. if (target == null)
  53. {
  54. target = new XElement("add", new XAttribute("key", key), new XAttribute("value", value ?? ""));
  55. root.Add(target);
  56. }
  57. else
  58. {
  59. target.SetAttributeValue("value", value ?? "");
  60. }
  61. doc.Save(path);
  62. }
  63. private static XDocument NewDoc() =>
  64. new XDocument(new XDeclaration("1.0", "utf-8", null), new XElement("appSettings"));
  65. }
  66. }