SharedConfigStore.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. var root = doc.Root;
  21. if (root == null) return null;
  22. foreach (var add in root.Elements("add"))
  23. {
  24. if ((string)add.Attribute("key") == key)
  25. return (string)add.Attribute("value");
  26. }
  27. return null;
  28. }
  29. catch
  30. {
  31. return null;
  32. }
  33. }
  34. /// <summary>写某键值(存在则更新,不存在则新增);文件不存在则创建片段骨架。</summary>
  35. public static void Write(string path, string key, string value)
  36. {
  37. XDocument doc;
  38. if (File.Exists(path))
  39. {
  40. try { doc = XDocument.Load(path); }
  41. catch { doc = NewDoc(); }
  42. }
  43. else
  44. {
  45. doc = NewDoc();
  46. }
  47. var root = doc.Root ?? new XElement("appSettings");
  48. if (doc.Root == null) doc.Add(root);
  49. XElement target = null;
  50. foreach (var add in root.Elements("add"))
  51. {
  52. if ((string)add.Attribute("key") == key) { target = add; break; }
  53. }
  54. if (target == null)
  55. {
  56. target = new XElement("add", new XAttribute("key", key), new XAttribute("value", value ?? ""));
  57. root.Add(target);
  58. }
  59. else
  60. {
  61. target.SetAttributeValue("value", value ?? "");
  62. }
  63. doc.Save(path);
  64. }
  65. private static XDocument NewDoc() =>
  66. new XDocument(new XDeclaration("1.0", "utf-8", null), new XElement("appSettings"));
  67. }
  68. }