C# 获取或设置指定 config 文件的值

ExeConfigurationFileMap 这个类提供了修改、获取指定 config 的功能;
新建一个 ExeConfigurationFileMap 的实例 ecf ;
并设置 ExeConfigFilename 属性为要操作的 config 文件路径;
使用 ConfigurationManager.OpenMappedExeConfiguration 方法得到操对象 Configuration config
调用 Configuration 对象实例提供的 config.AppSettings.Settings[key].Value 可以修改或者获取 appsetting 的值了;
如果修改需要调用一下保存方法,config.Save();

/// <summary>
/// 获取自定义 index.config 文件中的 appsetting 节点值
/// </summary>
/// <param name="key">节点名称</param>
/// <returns></returns>
public static string GetIndexConfigValue(string key)
{
string indexConfigPath = @"D:\indexConfig";
if (indexConfigPath.IsNullOrEmpty())
throw new Exception("请检查应用程序配置文件 appSettings 节点,是否存在 indexConfig 且 value 不为空的配置节!");
if (!File.Exists(indexConfigPath))
throw new Exception(string.Format("配置文件不存在:{0}", indexConfigPath));

ExeConfigurationFileMap ecf = new ExeConfigurationFileMap();
ecf.ExeConfigFilename = indexConfigPath;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(ecf, ConfigurationUserLevel.None);
return config.AppSettings.Settings[key].Value;
}
/// <summary>
/// 设置自定义 index.config 文件中的 appsetting 节点值
/// </summary>
/// <param name="key">节点名称</param>
/// <returns></returns>
public static bool SetIndexConfigValue(string key,string value)
{
string indexConfigPath = @"D:\indexConfig";
if (indexConfigPath.IsNullOrEmpty())
throw new Exception("请检查应用程序配置文件 appSettings 节点,是否存在 indexConfig 且 value 不为空的配置节!");
if (!File.Exists(indexConfigPath))
throw new Exception(string.Format("配置文件不存在:{0}", indexConfigPath));

ExeConfigurationFileMap ecf = new ExeConfigurationFileMap();
ecf.ExeConfigFilename = indexConfigPath;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(ecf, ConfigurationUserLevel.None);
config.AppSettings.Settings[key].Value = value;
config.Save();
return true;
}

转载请保留:http://www.iqingcao.com

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值