海海日记-冯海滨博客

您现在的位置是:首页 > C# > 正文

C#

c# 程序修改 config数据库配置文件方法

happyfhb2012-08-24C#1537

通常,app.config文件只允许读取,不允许写入,ConfigurationSettings.AppSettings和ConfigurationManager.AppSettings只是在程序第一次运行时候读取app.config到内存,一旦修改了app.config的值,就无法读取了,所以另外需要一个读取app.config的方法。另外,app.config在程序发布之后,名称会变更为应用程序名字.exe.config,在以下的方法里需要修改一下config文件的名字,暂时我先以config.xml文件命名,读取和更新写入app.config的方法
函数如下:
直接进行xml文件的读写

///

/// 写app.config
///

///
///
public void UpdateConfig(string key, string keyValue)
{
XmlDocument xmlDoc = new XmlDocument();
string configPath = "config.xml";
xmlDoc.Load(configPath);
XmlNode xmlNode = xmlDoc.SelectSingleNode("configuration/appSettings/add[@key='" + key + "']");
xmlNode.Attributes["value"].InnerText = keyValue;
xmlDoc.Save(configPath);
}
///

/// 读app.config
///

///
///
internal static string GetConfigValue(string key)
{
XmlDocument xmlDoc = new XmlDocument();
string configPath = "config.xml";
xmlDoc.Load(configPath);
XmlElement xElem = xmlDoc.SelectSingleNode("//appSettings/add[@key='" + key + "']") as XmlElement;
if (xElem != null)
return xElem.GetAttribute("value");
else
return string.Empty;
}

平淡中储蓄成长

发表评论

评论列表

  • 这篇文章还没有收到评论,赶紧来抢沙发吧~