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