c# 根据配置文件路径,设置和获取config文件 appSettings 节点值
一:获取和设置默认配置文件
/// <summary>
/// 获取编译后的主配置文件节点值 /// </summary> /// <param name="key"></param> /// <returns></returns> public static string GetConnectionStringsConfig(string key) { try { ExeConfigurationFileMap map = new ExeConfigurationFileMap { ExeConfigFilename = @"DMSystem.exe.config" }; var configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); return configuration.AppSettings.Settings[key].Value; } catch (Exception ex) { throw ex; } } /// <summary> /// 设置编译后的主配置文件节点值 /// </summary> /// <param name="key"></param> /// <returns></returns> public static void SetConnectionStringsConfig(string key, string value) { try { ExeConfigurationFileMap map = new ExeConfigurationFileMap { ExeConfigFilename = @"DMSystem.exe.config" }; var configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); bool isModified = false; //检测是否已经存在该键 foreach (string tempKey in configuration.AppSettings.Settings.AllKeys) { if (tempKey == key) { isModified = true; } } if (isModified) { configuration.AppSettings.Settings.Remove(key); } configuration.AppSettings.Settings.Add(key, value); configuration.Save(ConfigurationSaveMode.Modified); //刷新 ConfigurationManager.RefreshSection("appSettings"); } catch (Exception ex) { throw ex; } }
二、获取和设置指定配置文件
/// <summary> /// 获取指定config文件中appSettings节点下key的value /// </summary> /// <param name="key">appSettings > add > key </param> /// <param name="configPath">配置文件绝对路径</param> /// <returns></returns> public static string GetAppSettings(string key, string configPath) { ExeConfigurationFileMap map = new ExeConfigurationFileMap { ExeConfigFilename = configPath }; var configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); var strObj = configuration.AppSettings.Settings[key]; if (strObj == null) { throw new ArgumentException($"当前配置文件路径{configuration.FilePath}\n文件中appSettings节点下未配置名为:【{key}】的内容,请添加后再试"); } return strObj.Value; } /// <summary> /// 修改指定config文件中appSettings节点下key的value /// </summary> /// <param name="name">appSettings > add > key </param> /// <param name="configPath">配置文件绝对路径</param> /// <returns></returns> public static bool SetAppSettings(string key, string value, string configPath) { try { ExeConfigurationFileMap map = new ExeConfigurationFileMap { ExeConfigFilename = configPath }; var configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); if (configuration.AppSettings.Settings[key] != null) configuration.AppSettings.Settings[key].Value = value; else configuration.AppSettings.Settings.Add(key, value); configuration.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); return true; } catch { return false; } }