如何使用c#winform从appSettings获取给定配置文件的值?

时间:2015-10-02 14:14:42

标签: c# winforms c#-4.0 web-config

我正在提供.config文件路径,我想从给定的key=MYDATA文件中检索.config的appSetting值。

我尝试了以下代码但没有得到预期。

//System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        //var classLibrary1AppSettings = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationManager.GetSection("appSettings");

        //config.AppSettings.File = "C:\\mydemo\\web.config";
  

希望获得key=MYDATA

的价值

1 个答案:

答案 0 :(得分:1)

最后我能够管理它,发帖会帮助别人

System.Configuration.ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
            configFileMap.ExeConfigFilename = "C:\\mydemo\\web.config";

            System.Configuration.Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
            AppSettingsSection section = (AppSettingsSection)configuration.GetSection("appSettings");
            if (section.Settings.AllKeys.Any(key => key == "MYDATA"))
            {
                section.Settings["MYDATA"].Value = updateConfigId;
                configuration.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
            }