I have an app.config file that looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="TestKey" value="TestValue" />
</appSettings>
<newSection>
</newSection>
</configuration>
And I’m trying to use it in this way:
System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(@"C:\app.config");
System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
However, it doesn’t seem to be working. When I break and debug right after the file is read in, and I try to look at configuration.AppSettings I get an 'configuration.AppSettings' threw an exception of type 'System.InvalidCastException'.
I’m sure I’m reading the file, because when I look at configuration.Sections[“newSection”] I am returned an empty {System.Configuration.DefaultSection} (rather than null).
I’m guessing I’ve got something very basic wrong…what’s going on with AppSettings?
You are using a wrong function to read the app.config. OpenMappedMachineConfiguration is intended to open your machine.config file, but you are opening a typical application.exe.config file.
The following code will read your app.config and return what you’d expect.