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?
An application configuration file contains settings that are specific to an app. This file includes configuration settings that the common language runtime reads (such as assembly binding policy, remoting objects, and so on), and settings that the app can read.
Get config file for your Android appIn the Your apps card, select the package name of the app for which you need a config file. Click google-services. json. Move your config file into the module (app-level) directory of your app.
The application configuration file usually lives in the same directory as your application. For web applications, it is named Web. config. For non-web applications, it starts life with the name of App.
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.
System.Configuration.ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = @"C:\app.config";
System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
MessageBox.Show(configuration.AppSettings.Settings["TestKey"].Value);
I think the 'newSection' element is causing the problem. Unless you add a 'configSections' element too, to declare what 'newSection' is, .NET won't be able to cast it.
You need something like:
<configSections>
<section name="newSection" type="Fully.Qualified.TypeName.NewSection,
AssemblyName" />
</configSections>
In the first instance, I'd try removing the 'newSection' element to see if this improves the situation.
This link explains about Custom Configuration Sections.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With