C# 读取配置指定Config文件--亲测通过
直接上代码:
public class ConfigUtils { public static String GetKey(String configPath,String key) { Configuration ConfigurationInstance = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap() { ExeConfigFilename = configPath }, ConfigurationUserLevel.None); if (ConfigurationInstance.AppSettings.Settings[key] != null) return ConfigurationInstance.AppSettings.Settings[key].Value; else return string.Empty; } public static bool SetKey(String configPath, String key,String vls) { try { Configuration ConfigurationInstance = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap() { ExeConfigFilename = configPath }, ConfigurationUserLevel.None); if (ConfigurationInstance.AppSettings.Settings[key] != null) ConfigurationInstance.AppSettings.Settings[key].Value = vls; else ConfigurationInstance.AppSettings.Settings.Add(key, vls); ConfigurationInstance.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); return true; } catch { return false; } } }
使用方法:
public static bool SetXXXKey(String vls) { return ConfigUtils.SetKey(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "XXX.exe.config", "XXX",vls); } //XXX分别是文件名/Key名 public static String GetXXXKey() { return ConfigUtils.GetKey(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "XXX.exe.config", "XXX"); } //XXX分别是文件名/Key名