读语句:
String str = ConfigurationManager.AppSettings["DemoKey"];
写语句:
Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
cfa.AppSettings.Settings["DemoKey"].Value = "DemoValue";
cfa.Save();
配置文件内容格式:(app.config)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="DemoKey" value="*" />
</appSettings>
</configuration>
红笔标明的几个关键节是必须的
System.Configuration.ConfigurationSettings.AppSettings["Key"];
但是现在FrameWork2.0已经明确表示此属性已经过时。并建议改为ConfigurationManager或
WebConfigurationManager。并且AppSettings属性是只读的,并不支持修改属性值.
但是要想调用ConfigurationManager必须要先在工程里添加system.configuration.dll程序集的引用。
(在解决方案管理器中右键点击工程名称,在右键菜单中选择添加引用,.net TablePage下即可找到)
添加引用后可以用 String str = ConfigurationManager.AppSettings["Key"]来获取对应的值了。
更新配置文件:
Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
cfa.AppSettings.Settings.Add("key", "Name") || cfa.AppSettings.Settings["BrowseDir"].Value = "name";
等等...
最后调用
cfa.Save();
当前的配置文件更新成功。
参考1:
public class ConfigManager
{
System.Configuration.Configuration config = null;
public ConfigManager()
{
config=ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
}
/// <summary>
/// //添加键值
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void AddAppSetting(string key, string value)
{
config.AppSettings.Settings.Add(key, value);
config.Save();
}
/// <summary>
/// //修改键值
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void SaveAppSetting(string key, string value)
{
config.AppSettings.Settings.Remove(key);
config.AppSettings.Settings.Add(key, value);
config.Save();
}
/// <summary>
/// //获得键值
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string GetAppSetting(string key)
{
return config.AppSettings.Settings[key].Value;
}
/// <summary>
/// //移除键值
/// </summary>
/// <param name="key"></param>
public void DelAppSetting(string key)
{
config.AppSettings.Settings.Remove(key);
config.Save();
}
public ArrayList GetXmlElements(string strElem)
{
ArrayList list = new ArrayList();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
XmlNodeList listNode = xmlDoc.SelectNodes(strElem);
foreach (XmlElement el in listNode)
{
list.Add(el.InnerText);
}
return list;
}
}
参考2:
class Configuration
{
public static string fileName=System.IO.Path.GetFileName(Application.ExecutablePath);
public static bool addSetting(string key,string value){
Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(fileName);
config.AppSettings.Settings.Add(key, value);
config.Save();
return true;
}
public static string getSetting(string key){
Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(fileName);
string value=config.AppSettings.Settings[key].Value;
return value;
}
public static bool updateSeeting(string key, string newValue)
{
Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(fileName);
string value = config.AppSettings.Settings[key].Value=newValue;
config.Save();
return true;
}
}
参考3:public class ConfigureAppConfig
{
//静态构造,不能实例化
static ConfigureAppConfig() { } /** <summary>
/// 获取AppSettings配置节中的Key值
/// </summary>
/// <param name="keyName">Key's name</param>
/// <returns>Key's value</returns>
public static string GetAppSettingsKeyValue(string keyName)
{
return ConfigurationManager.AppSettings.Get(keyName);
} /** <summary>
/// 获取ConnectionStrings配置节中的值
/// </summary>
/// <returns></returns>
public static string GetConnectionStringsElementValue()
{
ConnectionStringSettings settings =System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"];
return settings.ConnectionString;
} /** <summary>
/// 保存节点中ConnectionStrings的子节点配置项的值
/// </summary>
/// <param name="elementValue"></param>
public static void ConnectionStringsSave(string ConnectionStringsName, string elementValue)
{
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["connectionString"].ConnectionString = elementValue;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
} /** <summary>
/// 判断appSettings中是否有此项
/// </summary>
private static bool AppSettingsKeyExists(string strKey, Configuration config)
{
foreach (string str in config.AppSettings.Settings.AllKeys)
{
if (str == strKey)
{
return true;
}
}
return false;
} /** <summary>
/// 保存appSettings中某key的value值
/// </summary>
/// <param name="strKey">key's name</param>
/// <param name="newValue">value</param>
public static void AppSettingsSave(string strKey, string newValue)
{
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (AppSettingsKeyExists(strKey, config))
{
config.AppSettings.Settings[strKey].Value = newValue;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
}
}
// 如果你的程序是对其它程序的配置文件进行操作,代码如下:
public class ConfigureAppConfig
{
//静态构造,不能实例化
static ConfigureAppConfig() { } /** <summary>
/// 获取AppSettings配置节中的Key值
/// </summary>
/// <param name="keyName">Key's name</param>
/// <returns>Key's value</returns>
public static string GetAppSettingsKeyValue(string keyName)
{
return ConfigurationManager.AppSettings.Get(keyName);
} /** <summary>
/// 获取ConnectionStrings配置节中的值
/// </summary>
/// <returns></returns>
public static string GetConnectionStringsElementValue()
{
ConnectionStringSettings settings =System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"];
return settings.ConnectionString;
} /** <summary>
/// 保存节点中ConnectionStrings的子节点配置项的值
/// </summary>
/// <param name="elementValue"></param>
public static void ConnectionStringsSave(string ConnectionStringsName, string elementValue)
{
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["connectionString"].ConnectionString = elementValue;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
} /** <summary>
/// 判断appSettings中是否有此项
/// </summary>
private static bool AppSettingsKeyExists(string strKey, Configuration config)
{
foreach (string str in config.AppSettings.Settings.AllKeys)
{
if (str == strKey)
{
return true;
}
}
return false;
} /** <summary>
/// 保存appSettings中某key的value值
/// </summary>
/// <param name="strKey">key's name</param>
/// <param name="newValue">value</param>
public static void AppSettingsSave(string strKey, string newValue)
{
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (AppSettingsKeyExists(strKey, config))
{
config.AppSettings.Settings[strKey].Value = newValue;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
}
}
ExeConfigurationFileMap filemap = new ExeConfigurationFileMap();
filemap.ExeConfigFilename = filePath;//配置文件路径
config = ConfigurationManager.OpenMappedExeConfiguration(filemap, ConfigurationUserLevel.None);
if (AppSettingsKeyExists("Refresh", config))
{
config.AppSettings.Settings["Refresh"].Value = M_TimeRead.ToString();
} if (AppSettingsKeyExists("MachineNo", config))
{
config.AppSettings.Settings["MachineNo"].Value = M_MachineNo; }
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
config.ConnectionStrings.ConnectionStrings["connectionString"].ConnectionString = M_ConnectionString;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
数据库字符串加密
ExeConfigurationFileMap filemap = new ExeConfigurationFileMap();
filemap.ExeConfigFilename = Application.ExecutablePath + ".Config"; //filePath;
config = ConfigurationManager.OpenMappedExeConfiguration(filemap, ConfigurationUserLevel.None);
//指定我所要的节点
ConfigurationSection section = config.ConnectionStrings;
if ((section.SectionInformation.IsProtected == false) && (section.ElementInformation.IsLocked == false))
{
//制定节点加密
section.SectionInformation.ProtectSection(protect);
//即使没有修改也保存设置
section.SectionInformation.ForceSave = true;
//配置文件内容保存到xml
config.Save(ConfigurationSaveMode.Full);
}
//==============================================
// FileName: ConfigManager
// Description: 静态方法业务类,用于对C#、ASP.NET中的WinForm & WebForm 项目程序配置文件
// app.config和web.config的[appSettings]和[connectionStrings]节点进行新增、修改、删除和读取相关的操作。
//==============================================
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using TempusMq;
namespace Kevin.DAL
{
public enum ConfigurationFile
{
AppConfig=1,
WebConfig=2
}
/// <summary>
/// ConfigManager 应用程序配置文件管理器
/// </summary>
public class ConfigManager
{
public ConfigManager()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 对[appSettings]节点依据Key值读取到Value值,返回字符串
/// </summary>
/// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
/// <param name="key">要读取的Key值</param>
/// <returns>返回Value值的字符串</returns>
public static string ReadValueByKey(ConfigurationFile configurationFile, string key)
{
string value = string.Empty;
string filename = string.Empty;
if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
{
filename = System.Windows.Forms.Application.ExecutablePath + ".config";
}
else
{
filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
}
XmlDocument doc = new XmlDocument();
doc.Load(filename); //加载配置文件
XmlNode node = doc.SelectSingleNode("//appSettings"); //得到[appSettings]节点
得到[appSettings]节点中关于Key的子节点
XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
if (element != null)
{
value = element.GetAttribute("value");
}
return value;
}
/// <summary>
/// 对[connectionStrings]节点依据name值读取到connectionString值,返回字符串
/// </summary>
/// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
/// <param name="name">要读取的name值</param>
/// <returns>返回connectionString值的字符串</returns>
public static string ReadConnectionStringByName(ConfigurationFile configurationFile, string name)
{
string connectionString = string.Empty;
string filename = string.Empty;
if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
{
filename = System.Windows.Forms.Application.ExecutablePath + ".config";
}
else
{
filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
}
XmlDocument doc = new XmlDocument();
doc.Load(filename); //加载配置文件
XmlNode node = doc.SelectSingleNode("//connectionStrings"); //得到[appSettings]节点
得到[connectionString]节点中关于name的子节点
XmlElement element = (XmlElement)node.SelectSingleNode("//add[@name='" + name + "']");
if (element != null)
{
connectionString = element.GetAttribute("connectionString");
}
return connectionString;
}
/// <summary>
/// 更新或新增[appSettings]节点的子节点值,存在则更新子节点Value,不存在则新增子节点,返回成功与否布尔值
/// </summary>
/// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
/// <param name="key">子节点Key值</param>
/// <param name="value">子节点value值</param>
/// <returns>返回成功与否布尔值</returns>
public static bool UpdateOrCreateAppSetting(ConfigurationFile configurationFile, string key, string value)
{
bool isSuccess = false;
string filename = string.Empty;
if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
{
filename = System.Windows.Forms.Application.ExecutablePath + ".config";
}
else
{
filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
}
XmlDocument doc = new XmlDocument();
doc.Load(filename); //加载配置文件
XmlNode node = doc.SelectSingleNode("//appSettings"); //得到[appSettings]节点
try
{
得到[appSettings]节点中关于Key的子节点
XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
if (element != null)
{
//存在则更新子节点Value
element.SetAttribute("value", value);
}
else
{
//不存在则新增子节点
XmlElement subElement = doc.CreateElement("add");
subElement.SetAttribute("key", key);
subElement.SetAttribute("value", value);
node.AppendChild(subElement);
}
//保存至配置文件(方式一)
using (XmlTextWriter xmlwriter = new XmlTextWriter(filename, null))
{
xmlwriter.Formatting = Formatting.Indented;
doc.WriteTo(xmlwriter);
xmlwriter.Flush();
}
isSuccess = true;
}
catch (Exception e)
{
isSuccess = false;
//输出的调试字符串
string strOuput = string.Format("更新或新增[appSettings]节点的子节点值失败:{0}\n", e.Message);
//将信息写入到日志输出文件
DllComm.TP_WriteAppLogFileEx(DllComm.g_AppLogFileName, strOuput);
}
return isSuccess;
}
/// <summary>
/// 更新或新增[appSettings]节点的子节点值,存在则更新子节点Value,不存在则新增子节点,返回成功与否布尔值
/// </summary>
/// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
/// <param name="key">子节点Key值</param>
/// <param name="value">子节点value值</param>
/// <returns>返回成功与否布尔值</returns>
public static bool UpdateOrCreateAppSetting(ConfigurationFile configurationFile,string configFileName,string key, string value)
{
bool isSuccess = false;
string filename = configFileName;
XmlDocument doc = new XmlDocument();
doc.Load(filename); //加载配置文件
XmlNode node = doc.SelectSingleNode("//appSettings"); //得到[appSettings]节点
try
{
得到[appSettings]节点中关于Key的子节点
XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
if (element != null)
{
//存在则更新子节点Value
element.SetAttribute("value", value);
}
else
{
//不存在则新增子节点
XmlElement subElement = doc.CreateElement("add");
subElement.SetAttribute("key", key);
subElement.SetAttribute("value", value);
node.AppendChild(subElement);
}
//保存至配置文件(方式一)
using (XmlTextWriter xmlwriter = new XmlTextWriter(filename, null))
{
xmlwriter.Formatting = Formatting.Indented;
doc.WriteTo(xmlwriter);
xmlwriter.Flush();
}
isSuccess = true;
}
catch (Exception e)
{
isSuccess = false;
//输出的调试字符串
string strOuput = string.Format("更新或新增[appSettings]节点的子节点值失败:{0}\n", e.Message);
//将信息写入到日志输出文件
DllComm.TP_WriteAppLogFileEx(DllComm.g_AppLogFileName, strOuput);
}
return isSuccess;
}
/// <summary>
/// 更新或新增[connectionStrings]节点的子节点值,存在则更新子节点,不存在则新增子节点,返回成功与否布尔值
/// </summary>
/// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
/// <param name="name">子节点name值</param>
/// <param name="connectionString">子节点connectionString值</param>
/// <param name="providerName">子节点providerName值</param>
/// <returns>返回成功与否布尔值</returns>
public static bool UpdateOrCreateConnectionString(ConfigurationFile configurationFile, string name, string connectionString, string providerName)
{
bool isSuccess = false;
string filename = string.Empty;
if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
{
filename = System.Windows.Forms.Application.ExecutablePath + ".config";
}
else
{
filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
}
XmlDocument doc = new XmlDocument();
doc.Load(filename); //加载配置文件
XmlNode node = doc.SelectSingleNode("//connectionStrings"); //得到[connectionStrings]节点
try
{
得到[connectionStrings]节点中关于Name的子节点
XmlElement element = (XmlElement)node.SelectSingleNode("//add[@name='" + name + "']");
if (element != null)
{
//存在则更新子节点
element.SetAttribute("connectionString", connectionString);
element.SetAttribute("providerName", providerName);
}
else
{
//不存在则新增子节点
XmlElement subElement = doc.CreateElement("add");
subElement.SetAttribute("name", name);
subElement.SetAttribute("connectionString", connectionString);
subElement.SetAttribute("providerName", providerName);
node.AppendChild(subElement);
}
//保存至配置文件(方式二)
doc.Save(filename);
isSuccess = true;
}
catch (Exception e)
{
isSuccess = false;
//输出的调试字符串
string strOuput = string.Format("更新或新增[connectionStrings]节点的子节点值:{0}失败:{1}\n",name,e.Message);
//将信息写入到日志输出文件
DllComm.TP_WriteAppLogFileEx(DllComm.g_AppLogFileName, strOuput);
}
return isSuccess;
}
/// <summary>
/// 删除[appSettings]节点中包含Key值的子节点,返回成功与否布尔值
/// </summary>
/// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
/// <param name="key">要删除的子节点Key值</param>
/// <returns>返回成功与否布尔值</returns>
public static bool DeleteByKey(ConfigurationFile configurationFile, string key)
{
bool isSuccess = false;
string filename = string.Empty;
if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
{
filename = System.Windows.Forms.Application.ExecutablePath + ".config";
}
else
{
filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
}
XmlDocument doc = new XmlDocument();
doc.Load(filename); //加载配置文件
XmlNode node = doc.SelectSingleNode("//appSettings"); //得到[appSettings]节点
得到[appSettings]节点中关于Key的子节点
XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
if (element != null)
{
//存在则删除子节点
element.ParentNode.RemoveChild(element);
}
else
{
//不存在
}
try
{
//保存至配置文件(方式一)
using (XmlTextWriter xmlwriter = new XmlTextWriter(filename, null))
{
xmlwriter.Formatting = Formatting.Indented;
doc.WriteTo(xmlwriter);
xmlwriter.Flush();
}
isSuccess = true;
}
catch (Exception e)
{
//输出的调试字符串
string strOuput = string.Format("删除[appSettings]节点中包含Key:{0}值的子节点失败:{1}\n",key, e.Message);
//将信息写入到日志输出文件
DllComm.TP_WriteAppLogFileEx(DllComm.g_AppLogFileName, strOuput);
}
return isSuccess;
}
/// <summary>
/// 删除[connectionStrings]节点中包含name值的子节点,返回成功与否布尔值
/// </summary>
/// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
/// <param name="name">要删除的子节点name值</param>
/// <returns>返回成功与否布尔值</returns>
public static bool DeleteByName(ConfigurationFile configurationFile, string name)
{
bool isSuccess = false;
string filename = string.Empty;
if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
{
filename = System.Windows.Forms.Application.ExecutablePath + ".config";
}
else
{
filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
}
XmlDocument doc = new XmlDocument();
doc.Load(filename); //加载配置文件
XmlNode node = doc.SelectSingleNode("//connectionStrings"); //得到[connectionStrings]节点
得到[connectionStrings]节点中关于Name的子节点
XmlElement element = (XmlElement)node.SelectSingleNode("//add[@name='" + name + "']");
if (element != null)
{
//存在则删除子节点
node.RemoveChild(element);
}
else
{
//不存在
}
try
{
//保存至配置文件(方式二)
doc.Save(filename);
isSuccess = true;
}
catch (Exception e)
{
isSuccess = false;
//输出的调试字符串
string strOuput = string.Format("删除[connectionStrings]节点中包含name:{0}值的子节点失败:{1}\n",name,e.Message);
//将信息写入到日志输出文件
DllComm.TP_WriteAppLogFileEx(DllComm.g_AppLogFileName, strOuput);
}
return isSuccess;
}
}
}