public static class AppSettingHelper
{
/// <summary>
/// 从AppSetting中获取配置数据
/// </summary>
/// <typeparam name="T">获取的配置数据类型</typeparam>
/// <param name="key">配置KEY名</param>
/// <param name="defaultValue">默认值,获取失败返回的值</param>
/// <returns></returns>
/// <summary>
public static T GetAppSettingValue<T>(string key, T defaultValue)
{
if (string.IsNullOrEmpty(key))
{
return defaultValue;
}
if (ConfigurationManager.AppSettings.Get(key) == null)
{
SetConfigValue(key, defaultValue.ToString());
}
else
{
string value = ConfigurationManager.AppSettings[key];
if (!string.IsNullOrEmpty(value))
{
try
{
defaultValue = (T)Convert.ChangeType(value, typeof(T));
}
catch
{
}
}
}
return defaultValue;
}
/// <summary>
/// 修改AppSettings中配置
/// </summary>
/// <param name="key">key值</param>
/// <param name="value">相应值</param>
public static bool SetConfigValue(string key, string value)
{
try
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] != null)
config.AppSettings.Settings[key].Value = value;
else
config.AppSettings.Settings.Add(key, value);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
return true;
}
catch
{
return false;
}
}
public static string GetConnectionString(string key)
{
return ConfigurationManager.ConnectionStrings[key]?.ConnectionString;
}
public static bool SetConnectionString(string key, string newConnStr, string providerName)
{
try
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
XmlDocument doc = new XmlDocument();
doc.Load(config.FilePath);
XmlNode root = doc.SelectSingleNode("configuration");
XmlNode node = root.SelectSingleNode($"connectionStrings/add[@name='{key}']");
if (node == null)
{
if (string.IsNullOrEmpty(providerName))
{
config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(key, newConnStr));
}
else
{
config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(key, newConnStr, providerName));
}
config.Save(ConfigurationSaveMode.Modified);
}
else
{
XmlElement el = node as XmlElement;
el.SetAttribute("connectionString", newConnStr);
doc.Save(config.FilePath);
}
ConfigurationManager.RefreshSection("connectionStrings");
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var newVal = ConfigurationManager.ConnectionStrings[key];
var flag = newVal.ConnectionString == newConnStr;
return flag;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return false;
}
}
可生成默认配置setting,同时修改配置文件,配置有记忆功能!