在做Winform開發時,免不了把一些配置信息寫到APP.CONFIG文件中,當程序生成後APP.CONFIG會變成以程序名+CONFIG的文件即,如程序名為A,那麼生成後的APP.CONFIG文件會變成A.EXE.CONFIG文件!
直接上代碼,不解釋:
/// <summary>
/// 配置類型
/// </summary>
public enum configType { appSettings, connectionStrings }
public static string GetConfig(configType cType, string keyOrName)
{
string result = string.Empty;
if (cType == configType.appSettings) result = System.Configuration.ConfigurationManager.AppSettings[keyOrName];
else if (System.Configuration.ConfigurationManager.ConnectionStrings[keyOrName] != null)
result = System.Configuration.ConfigurationManager.ConnectionStrings[keyOrName].ConnectionString;
return result == null ? string.Empty : result;
}
/// <summary>
/// 讀取應用程序配置值,無相應項則返回String.Empty
/// </summary>
/// <param name="key">配置標識碼</param>
/// <returns></returns>
public static string GetAppSettings(string key)
{
return GetConfig(configType.appSettings, key);
}
/// <summary>
/// 修改或新建配置項 www.2cto.com
/// </summary>
/// <param name="key">配置標識碼</param>
/// <param name="val">配置項的值</param>
public static void SetAppSettings(string key, string val)
{
SetConfig(configType.appSettings, key, val);
}
public static void SetConfig(configType cType, string keyOrName, string val) //傳2個參數 一個是配置文件鍵的名字,一個是要給這個鍵的值
{
try
{
XmlDocument xDoc = new XmlDocument(); //定義XmlDocument,想操作xml一般都用這個類
string path = biovision.ihospital.his.dbCommon.db.configFilePath; //獲取App.config文件絕對路徑
//string str = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase; //這是獲取配置文件路徑的
//str = str.Substring(0, str.Length - 10) + "App.config"; //這是獲取配置文件的名稱
xDoc.Load(path); //讀取xml
XmlNode xNode; //xml節點
XmlElement xElemCurrent; //xml元素
XmlElement xElemNew; //xml元素
if (cType == configType.connectionStrings)
{
xNode = xDoc.SelectSingleNode("//connectionStrings");
xElemCurrent = (XmlElement)xNode.SelectSingleNode("//add[@name='" + keyOrName + "']");
if (xElemCurrent != null)
xElemCurrent.SetAttribute("connectionString", val);//如果有這個鍵就給他賦值
else
{//沒有這個鍵就添加一個鍵並且賦值
xElemNew = xDoc.CreateElement("add");
xElemNew.SetAttribute("name", keyOrName);
xElemNew.SetAttribute("connectionString", val);
xElemNew.SetAttribute("providerName", "System.Data.SqlClient");
xNode.AppendChild(xElemNew);
}
}
else
{
xNode = xDoc.SelectSingleNode("//appSettings");
xElemCurrent = (XmlElement)xNode.SelectSingleNode("//add[@key='" + keyOrName + "']");
if (xElemCurrent != null)
xElemCurrent.SetAttribute("value", val);//如果有這個鍵就給他賦值 AppValue 就是值
else
{//沒有這個鍵就添加一個鍵並且賦值
xElemNew = xDoc.CreateElement("add");
xElemNew.SetAttribute("key", keyOrName);
xElemNew.SetAttribute("value", val);
xNode.AppendChild(xElemNew);
}
}
xDoc.Save(path);
}
catch (Exception e)
{
Log.LogException(e, "寫config配置文件出錯。");
}
}
後來仔細想一想,其實還有下面一種方法也可以實現config的讀寫功能(MS提供的,可能更好)
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings[key].Value = value;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(“appSettings”);
摘自 欲將心事訴東風,無怨滿城風得意~