using System.IO; using System.Xml.Linq; namespace ivf_tl_Operate.Helpers { /// /// 配置收敛:operate↔control 共享连接键的唯一数据源文件(tl-shared.config)读写。 /// 文件格式 = 独立 appSettings 片段(<appSettings><add key.. value../></appSettings>), /// 正是 <appSettings file="…"> 期望的外部文件格式 → 两进程经 file= 只读合并即读到。 /// 用 XDocument 直写,绕开 ConfigurationManager 写回 file= 的不确定行为。 /// public static class SharedConfigStore { /// 读片段文件里某键值;文件不存在或键缺失返回 null。 public static string Read(string path, string key) { if (!File.Exists(path)) return null; try { var doc = XDocument.Load(path); var root = doc.Root; if (root == null) return null; foreach (var add in root.Elements("add")) { if ((string)add.Attribute("key") == key) return (string)add.Attribute("value"); } return null; } catch { return null; } } /// 写某键值(存在则更新,不存在则新增);文件不存在则创建片段骨架。 public static void Write(string path, string key, string value) { XDocument doc; if (File.Exists(path)) { try { doc = XDocument.Load(path); } catch { doc = NewDoc(); } } else { doc = NewDoc(); } var root = doc.Root ?? new XElement("appSettings"); if (doc.Root == null) doc.Add(root); XElement target = null; foreach (var add in root.Elements("add")) { if ((string)add.Attribute("key") == key) { target = add; break; } } if (target == null) { target = new XElement("add", new XAttribute("key", key), new XAttribute("value", value ?? "")); root.Add(target); } else { target.SetAttributeValue("value", value ?? ""); } doc.Save(path); } private static XDocument NewDoc() => new XDocument(new XDeclaration("1.0", "utf-8", null), new XElement("appSettings")); } }