前言
在项目当中为了增加软件的灵活性及可配置性,配置文件在程序当中起着不可替代的作用。下面介绍一下最近用的比较多的方式。
config文件的操作
数据库连接字符串
1.获取连接字符串
public static string GetConnectionStrings(string connectionName)
{
string file = Application.ExecutablePath;
Configuration config = ConfigurationManager.OpenExeConfiguration(file);
string connectionString = config.ConnectionStrings.ConnectionStrings[connectionName].ConnectionString.ToString();
return connectionString;
}
2.更新连接字符串
///<summary>
///更新连接字符串
///</summary>
///<param name="newName">连接字符串名称</param>
///<param name="newConString">连接字符串内容</param>
///<param name="newProviderName">数据提供程序名称</param>
public static void UpdateConnectionStringsConfig(string newName, string newConString, string newProviderName)
{
//指定config文件读取
string file = System.Windows.Forms.Application.ExecutablePath;
Configuration config = ConfigurationManager.OpenExeConfiguration(file);
bool exist = false; //记录该连接串是否已经存在
//如果要更改的连接串已经存在
if (config.ConnectionStrings.ConnectionStrings[newName] != null)
{
exist = true;
}
// 如果连接串已存在,首先删除它
if (exist)
{
config.ConnectionStrings.ConnectionStrings.Remove(newName);
}
//新建一个连接字符串实例
ConnectionStringSettings mySettings =
new ConnectionStringSettings(newName, newConString, newProviderName);
// 将新的连接串添加到配置文件中.
config.ConnectionStrings.ConnectionStrings.Add(mySettings);
// 保存对配置文件所作的更改
config.Save(ConfigurationSaveMode.Modified);
// 强制重新载入配置文件的ConnectionStrings配置节
ConfigurationManager.RefreshSection("connectionStrings");
}
//返回config文件中AppSettings配置节的value值
public static string GetAppConfig(string strKey)
{
string file = Application.ExecutablePath;
Configuration config = ConfigurationManager.OpenExeConfiguration(file);
foreach( string key in config.AppSettings.Settings.AllKeys)
{
if (key == strKey)
{
return config.AppSettings.Settings[strKey].Value.ToString();
}
}
return null;
}
键值对配置
1.在配置节增加一对键值对
/// <summary>
/// 在appSettings配置节增加一对键值对
/// </summary>
/// <param name="newKey">键</param>
/// <param name="newValue">值</param>
public static void AddAppConfig(string newKey, string newValue)
{
string file = System.Windows.Forms.Application.ExecutablePath;
Configuration config = ConfigurationManager.OpenExeConfiguration(file);
bool exist = false;
foreach (string key in config.AppSettings.Settings.AllKeys)
{
if (key == newKey)
{
exist = true;
}
}
if (exist)
{
config.AppSettings.Settings.Remove(newKey);
}
config.AppSettings.Settings.Add(newKey, newValue);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
2.获取配置节中键值对的值
/// <summary>
/// 返回config文件中AppSettings配置节的value值
/// </summary>
/// <param name="strKey">键</param>
/// <returns></returns>
public static string GetAppConfig(string strKey)
{
string file = Application.ExecutablePath;
Configuration config = ConfigurationManager.OpenExeConfiguration(file);
foreach( string key in config.AppSettings.Settings.AllKeys)
{
if (key == strKey)
{
return config.AppSettings.Settings[strKey].Value.ToString();
}
}
return null;
}