C# 获取app.config中的信息

  • Post author:
  • Post category:其他


/// <summary>

/// 读操作

/// </summary>

/// <param name=”appKey”></param>

/// <returns></returns>

public string GetConfigValue(string appKey)

{

XmlDocument xDoc = new XmlDocument();

try

{

xDoc.Load(System.Windows.Forms.Application.ExecutablePath + “.config”);

XmlNode xNode;

XmlElement xElem;

xNode = xDoc.SelectSingleNode(“//appSettings”);

xElem = (XmlElement)xNode.SelectSingleNode(“//add[@key='” + appKey + “‘]”);

if (xElem != null)

return xElem.GetAttribute(“value”);

else

return “”;

}

catch (Exception)

{

return “”;

}

}

///在config中设置想要的值

public static void SetValue(string AppKey, string AppValue)

{


XmlDocument xDoc = new XmlDocument();

//获取可执行文件的路径和名称

xDoc.Load(System.Windows.Forms.Application.ExecutablePath + “.config”);

XmlNode xNode;

XmlElement xElem1;

XmlElement xElem2;

xNode = xDoc.SelectSingleNode(“//appSettings”);

xElem1 = (XmlElement)xNode.SelectSingleNode(“//add[@key='” + AppKey + “‘]”);

if (xElem1 != null) xElem1.SetAttribute(“value”, AppValue);

else

{


xElem2 = xDoc.CreateElement(“add”);

xElem2.SetAttribute(“key”, AppKey);

xElem2.SetAttribute(“value”, AppValue);

xNode.AppendChild(xElem2);

}

xDoc.Save(System.Windows.Forms.Application.ExecutablePath + “.config”);

}

///更新config的值

public static void UpdateConfig(string p_strKey, string p_strValue)

{


try

{


string m_strFullPath = “”;

// Assembly Asm = Assembly.GetExecutingAssembly();

XmlDocument xmlDoc = new XmlDocument();

m_strFullPath = System.Windows.Forms.Application.ExecutablePath + “.config”;

xmlDoc.Load(m_strFullPath);

XmlNodeList nodeList = xmlDoc.SelectSingleNode(“/configuration/appSettings”).ChildNodes;

foreach (XmlNode xn in nodeList)

{


XmlElement xe = (XmlElement)xn;

if (xe.GetAttribute(“key”).IndexOf(p_strKey) != -1)

{


xe.SetAttribute(“value”, p_strValue);

}

}

xmlDoc.Save(m_strFullPath);

}

catch (System.NullReferenceException NullEx)

{


throw NullEx;

}

catch (Exception ex)

{


throw ex;

}

}

用时候ConfigurationManager.AppSettings[“ImageCacheLocation”]获取config的值获取不到可以使用GetConfigValue();



版权声明:本文为u011470119原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。