/*----------------------------------------------------------------
// Copyright (C) 2009 ¹ãÖݺ²Óî¼ÆËã»ú¿Æ¼¼ÓÐÏÞ¹«Ë¾
// ÎļþÃû£ºConfigHelper.cs
// ×÷ÕߣºÂ½ÈÙ´º
// ÈÕÆÚ£º2009-5-10
// Îļþ¹¦ÄÜÃèÊö£ºÅäÖÃÎļþ¶ÁÈ¡Óë±£´æµÄÀà¡£
//
// ´´½¨±êʶ£º2009.06.17 °æ±¾£º1.0 LuRongChun ´´½¨¡£
// Ð޸ıêʶ£º
// Ð޸ıêʶ£º
//----------------------------------------------------------------*/
using System;
using System.Xml;
using System.Text;
using System.Configuration;
namespace BatchService.Framework.Utility
{
///
/// ÅäÖÃÎļþ¶ÁÈ¡Óë±£´æµÄÀà
///
public class ConfigHelper
{
#region ¶ÁÈ¡ÅäÖÃÎļþ
///
/// ´ÓApp.ConfigÖеÄappSettingsÖÐÈ¡add...µÄ²ÎÊýÖµ
///
/// add key='myKey' ÖеÄkeyÖµ(myKey)
/// Ô¤ÉèÖµ£¬µ±Ã»ÓÐkey»òkeyûÓÐֵʱ£¬·µ»ØdefaultValue
/// keyµÄ¶ÔÓ¦Öµ(add key='myKey' value='myVal'ÖеÄmyVal)
public static string ReadConfig(String key, String defaultValue = "")
{
try
{
Object setting = ConfigurationManager.AppSettings[key];
return (setting == null) ? defaultValue : (string)setting;
}
catch
{
return defaultValue;
}
}
public static string ReadConnectionConfig(String key, String defaultValue = "")
{
try
{
var setting = ConfigurationManager.ConnectionStrings[key];
return (setting == null) ? defaultValue : setting.ConnectionString;
}
catch
{
return defaultValue;
}
}
#endregion
#region ±£´æÅäÖÃÎļþ
///
/// ±£´æÅäÖÃÎļþ
///
///
///
public static void SetKeyValue(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("//configuration/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");
}
static public void UpdateConfig(string section, string key, string value)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ClientSettingsSection applicationSettingsSection = (ClientSettingsSection)config.SectionGroups["configuration"].Sections[section];
SettingElement element = applicationSettingsSection.Settings.Get(key);
if (null != element)
{
applicationSettingsSection.Settings.Remove(element);
element.Value.ValueXml.InnerXml = value;
applicationSettingsSection.Settings.Add(element);
}
else
{
element = new SettingElement(key, SettingsSerializeAs.String);
element.Value = new SettingValueElement();
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
element.Value.ValueXml = doc.CreateElement("value");
element.Value.ValueXml.InnerXml = value;
applicationSettingsSection.Settings.Add(element);
}
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("configuration");
}
#endregion
}
}