I've been trying all the possible ways and I still can not. In my first application, my configuration file will only have one option. My first application is only going to read it, nothing more.
My second application, will read the configuration file of the first application and can make changes.
This is my app.config:
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings"
type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="TCambio.Properties.Settings"
type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
</sectionGroup>
</configSections>
<appSettings>
<add key="thoras" value="3"/>
</appSettings>
</configuration>
And to read the key thoras, in my second application I do the following:
ConfigurationFileMap fileMap = new ConfigurationFileMap(strfilenamepath);
Configuration configuration = ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
try
{
string value = configuration.AppSettings.Settings["thoras"].Value;
MessageBox.Show(value);
}
catch (Exception ex)
{
MessageBox.Show("Error loading file. " + ex.Message);
}
But I got the following error:
Unable to cast object of type 'System.Configuration.DefaultSection' to type 'System.Configuration.AppSettingsSection'
The issue that you're having is due to using the OpenMappedMachineConfiguration
method on ConfigurationManager. This is used to access the machine level .config file, rather than one for a specific application.
If you update your code to:
var fileMap = new ExeConfigurationFileMap
{
ExeConfigFilename = strfilenamepath
};
var configuration = ConfigurationManager.OpenMappedExeConfiguration(
fileMap, ConfigurationUserLevel.None);
So that you're instead accessing the configuration for an application, you should find that the call to MessageBox.Show
will now succeed and show the number '3'.