Search code examples
c#winformsc#-4.0web-config

how to get value from appSettings for given config file using c# winform?


I'm giving .config file path and i want to retrieve appSetting value for key=MYDATA from that given .config file.

I tried following code but not getting expected.

//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";

want to get value for key=MYDATA


Solution

  • Finally I able to manage it:

    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");
                }