讀取,設定指定目錄下的配置檔案的節點key value。config或XML
阿新 • • 發佈:2018-11-29
public static string GetValue(string key)//讀取指定節點 { XmlDocument doc = new XmlDocument(); string nodeVal = string.Empty; try { doc.Load(HttpContext.Current.Server.MapPath("/Config/AppSetings.config"));//路徑 XmlNode node; XmlElement element; node = doc.SelectSingleNode("//" + "appSettings");//父節點 element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");//add 節點的 key名稱 if (element != null) { nodeVal = element.GetAttribute("value"); } return nodeVal; } catch (Exception) { return ""; throw; } }
/// <summary> /// 根據Key修改Value /// </summary> /// <param name="key">要修改的Key</param> /// <param name="value">要修改為的值</param> public static void SetValue(string key, string value) { FileInfo fi = new FileInfo(HttpContext.Current.Server.MapPath("/Config/AppSetings.config")); //判斷檔案屬性是否只讀?是則修改為一般屬性 if (fi.IsReadOnly==true) { fi.IsReadOnly = false; } System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument(); xDoc.Load(HttpContext.Current.Server.MapPath("/Config/AppSetings.config")); System.Xml.XmlNode xNode; System.Xml.XmlElement xElem1; System.Xml.XmlElement xElem2; xNode = xDoc.SelectSingleNode("//appSettings"); xElem1 = (System.Xml.XmlElement)xNode.SelectSingleNode("//add[@key='" + key + "']"); if (xElem1 != null) xElem1.SetAttribute("value", value); else { xElem2 = xDoc.CreateElement("add"); xElem2.SetAttribute("key", key); xElem2.SetAttribute("value", value); xNode.AppendChild(xElem2); } xDoc.Save(HttpContext.Current.Server.MapPath("/Config/AppSetings.config")); }
第二種方法修改
/// <summary> /// 修改web.config中appSettings鍵的值 /// </summary> /// <param name="configPath">web.config路徑</param> /// <param name="keyName">鍵的名稱</param> /// <param name="keyValue">鍵的值</param> public void UpdAppSettings(string configPath,string keyName,string keyValue) { XmlDocument doc = new XmlDocument(); try { doc.Load(configPath); XmlNode node; XmlElement element; node = doc.SelectSingleNode("//appSettings"); element = (XmlElement)node.SelectSingleNode("//add[@key='" + keyName + "']"); if (element != null) { element.SetAttribute("value", keyValue); doc.Save(configPath); } } catch (Exception) { throw; } }