C#动态操作Config文件Web.Winform通用
此方法是使用代码动态修改配置文件,asp.net通用,WEB.Config,App.Config 都可用sing System.Configuration;
namespace Zwj.TEMS.Common
{
public abstract class ConfigHelper
{
private ConfigHelper()
{ }
/// <summary>
/// 获取配置值
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static string GetAppSettingValue(string key)
{
return ConfigurationManager.AppSettings;
}
/// <summary>
/// 设置配置值(存在则更新,不存在则新增)
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public static void SetAppSettingValue(string key, string value)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var setting = config.AppSettings.Settings;
if (setting==null)
{
config.AppSettings.Settings.Add(key, value);
}
else
{
setting.Value = value;
}
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
/// <summary>
/// 删除配置值
/// </summary>
/// <param name="key"></param>
public static void RemoveAppSetting(string key)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove(key);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
/// <summary>
/// 获取连接字符串
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static string GetConnectionString(string name)
{
returnConfigurationManager.ConnectionStrings.ConnectionString;
}
/// <summary>
/// 设置连接字符串的值(存在则更新,不存在则新增)
/// </summary>
/// <param name="name"></param>
/// <param name="connstr"></param>
/// <param name="provider"></param>
public static void SetConnectionString(string name,string connstr, string provider)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConnectionStringSettings connStrSettings = config.ConnectionStrings.ConnectionStrings;
if (connStrSettings != null)
{
connStrSettings.ConnectionString = connstr;
connStrSettings.ProviderName = provider;
}
else
{
connStrSettings = new ConnectionStringSettings(name, connstr, provider);
config.ConnectionStrings.ConnectionStrings.Add(connStrSettings);
}
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
}
/// <summary>
/// 删除连接字符串配置项
/// </summary>
/// <param name="name"></param>
public static void RemoveConnectionString(string name)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings.Remove(name);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
}
}
}
页:
[1]