Read appSettings section from Web.config file using WebConfigurationManager - c#

I'm developing a WinForm application with C# and .NET Framework 4.7.
I want to open a Web.config file, read its appSetting section and modify it.
To open it, I use this:
System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(null);
It opens it but, when I try to get the keys with:
string[] keys = config.AppSettings.Settings.AllKeys;
I get a null array.
This is the appSetting section:
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<connectionStrings>
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="MinRemainingCodes" value="100" />
<!-- Others keys -->
</appSettings>
</configuration>
Maybe the problem is that it is not opening the file, but in the documentation say:
The virtual path to the configuration file. If null, the root
Web.config file is opened.
Maybe I don't understand what means with root because the program and the Web.config file are in the same folder.
What am I doing wrong?

WebConfigurationManager.OpenWebConfiguration includes the following description of the path parameter:
The virtual path to the configuration file. If null, the root Web.config file is opened.
Because your application is not running under IIS as a Web Site, the Web.config that is being opened is actually that which lives in the .NET Framework installation folder itself (in my case, that's C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config).
WebConfigurationManager.OpenMappedWebConfiguration allows you to map virtual directories to physical directories in order to allow you to specify a virtual path that is mapped to your own local directory. Here's the code I've used to make this work:
var webConfigurationFileMap = new WebConfigurationFileMap();
webConfigurationFileMap.VirtualDirectories.Add(
string.Empty,
new VirtualDirectoryMapping(Directory.GetCurrentDirectory(), isAppRoot: true));
var webConfig = WebConfigurationManager.OpenMappedWebConfiguration(
webConfigurationFileMap,
string.Empty);
As you can see, I'm mapping the root virtual directory (using string.Empty) to the application's directory (using Directory.GetCurrentDirectory).

OpenWebConfiguration is supposed to receive the path to your web config if I'm not mistaken and you are passing it null.
Try like this:
config = WebConfigurationManager.OpenWebConfiguration("~");
Also this might help you: How do you modify the web.config appSettings at runtime?

Well, first of all, you use web.config for a desktop application. It doesn't sound correct. Try to use app.config instead.
Second, WebConfigurationManager.OpenWebConfiguration opens the Web-application configuration file
As for the topic, to get information from the config file try to use
var keys = ConfigurationManager.AppSettings.AllKeys

Related

App.config file not being recognized in by PayPal.Api

I want to eventually set up Paypal payment. Step one though is to have a play. And I have failed on the quick start!
https://github.com/paypal/PayPal-NET-SDK/wiki/Quick-Start shows a code example. It explains that first, I need to download the PayPal .NET SDK package via NuGet. This is great, I'm on .NET Framework (not core). I install it.
Phase 2 gives an entire example. I add some PayPal config settings to the app.config file. Done
Phase 3 is where it is going wrong. I'm referencing PayPal.API in my C# class.
The relevant part of my code is
using PayPal.Api;
using System.Collections.Generic;
namespace TestProj.Payment
{
public class PaypalGateway
{
public void Sandbox()
{
var config = ConfigManager.Instance.GetProperties();// this is the fault
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
config always has 0 instances
My Project has an App.config file with the correct values
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="paypal" type="PayPal.SDKConfigHandler, PayPal" />
</configSections>
<paypal>
<settings>
<add name="mode" value="sandbox" />
<add name="clientId" value="***" />
<add name="clientSecret" value="***" />
</settings>
</paypal>
If I rename my App.config file to blah.nonsense then the same issue occurs. It's as if the API is looking for a file else where or that it isn't configured correctly.
This question is tagged with asp.net-mvc, so the assumption is that this is for a web project
The quick start clearly states
Add the following to your web.config or app.config
web.config should where you place the configuration details if this is in fact a web project.
Even if the referenced code is for another class library in the project, which can use app.config file, all the settings will eventually have to be in the root web.config file of the web project as that is the process that will be running.
the same problem was with me, the keyword PayPal must be in small caps like paypal.
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="paypal" type="PayPal.SDKConfigHandler, **PayPal**" />
</configSections>
<paypal>
<settings>
<add name="mode" value="sandbox" />
<add name="clientId" value="***" />
<add name="clientSecret" value="***" />
</settings>
</paypal>
should be
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="paypal" type="PayPal.SDKConfigHandler, **paypal**" />
</configSections>
<paypal>
<settings>
<add name="mode" value="sandbox" />
<add name="clientId" value="***" />
<add name="clientSecret" value="***" />
</settings>
</paypal>

Accessing Settings in different ways

I have a new (test) console application that I'm trying to access the settings.
When I attempt to access it this way, from what I've read on SO and other places, this should work:
var test1 = System.Configuration.ConfigurationManager.AppSettings["MySetting"];
but it doesn't, it returns null.
When I do it this way, it works fine:
var test2 = Properties.Settings.Default.MySetting;
Why doesn't the first one work? Everything I've read shows to use it the first way.
Am I using it incorrectly?
EDIT
In response to Mason.
I'm confused on your comment. The app.config is where the setting is being set from the properties of the application:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="ConsoleApp1.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
</startup>
<applicationSettings>
<ConsoleApp1.Properties.Settings>
<setting name="MySetting" serializeAs="String">
<value>testtesttest</value>
</setting>
</ConsoleApp1.Properties.Settings>
</applicationSettings>
</configuration>
System.Configuration.ConfigurationManager.AppSettings is for reading settings from the app.config or web.config files (for ASP.NET). It does not read from the settings files.
Because AppSettings refers to reading the settings in MyApp.config

Edit app.config file and read settings

I have a app.config file.
I have settings there.
I want to modify settings after my build and then read it from file.
I mean I want to change settings by edeting a file.
I know how to change settings programmaticaly but I need it by editing file.
No I'm trying to do so:
private void ReadSettings()
{
string appPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string settingsPath = Path.Combine(appPath, "app.config");
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = settingsPath;
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
string value=config.AppSettings.Settings["Type"].Value;
}
My settings:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="RxTest.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<MyApp.Properties.Settings>
<setting name="Type" serializeAs="String">
<value>document</value>
</setting>
</RxTest.Properties.Settings>
</userSettings>
</configuration>
Problem is that there is nothing in Settings property.
What shuld I do to read settings from edeted file?
The UserSettings written in your app.config file should be automatically added into it by adding an entry into your properties.
You can achieve getting the values from your properties like this:
string value = Properties.Settings.Default.Type;
EDIT I:
To be sure you always have the freshest value, you can either refresh a section:
ConfigurationManager.RefreshSection(sectionName);
Or you can reaload the file:
Properties.Settings.Default.Reload();

Which App.config is current?

I'm running Visual Studio 12.0 targeting 4.5. I'm running VS Express. My App.config looks like this:
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="ConfigMgrTest2.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<applicationSettings>
<ConfigMgrTest2.Properties.Settings>
<setting name="exampleAppSetting" serializeAs="String">
<value>example app setting data</value>
</setting>
</ConfigMgrTest2.Properties.Settings>
</applicationSettings>
</configuration>
This allows me to use this syntax to access values:
string value = ConfigMgrTest2.Properties.Default.exampleAppSetting;
It seems from my research that I should have an "appSettings" section in my App.config that uses key-value pairs and looks like this:
<appSettings>
<add key="exampleAppSetting" value="example app setting data"/>
</appSettings>
This would allow me to access values like this:
string key = "exampleAppSetting";
var appSettings = System.Configuration.ConfigurationManager.AppSettings;
string value = appSettings[key];
Using my App.config, any call to the ConfigurationManager.AppSettings property is obviously returning null.
The question is, Which version of App.config is "right"?
Both are right and current.
In your example,
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="ConfigMgrTest2.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
You have simply used System.Configuration.ApplicationSettingsGroup to define a new configuration group applicationSettings.
if you were to add this to your config file:
<appSettings>
<add key="Alfa" value="42"/>
</appSettings>
You could still retrieve it with:
var alfa = ConfigurationManager.AppSettings["Alfa"];
Update
Full App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="ConfigMgrTest2.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<applicationSettings>
<ConfigMgrTest2.Properties.Settings>
<setting name="exampleAppSetting" serializeAs="String">
<value>example app setting data</value>
</setting>
</ConfigMgrTest2.Properties.Settings>
</applicationSettings>
<appSettings>
<add key="Alfa" value="42"/>
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Personally, I prefer custom configurations, since they allow me to provide for default values, as well as make some mandatory.
I am not sure about which version is proper, which may depend on your actual usage scenario but if you have the posted section in your app.config like below
<appSettings>
<add key="exampleAppSetting" value="example app setting data"/>
</appSettings>
Then you need to access it like below. You need to mention the KEY for which you are trying to get the value.
ConfigurationManager.AppSettings["exampleAppSetting"]
Assuming you have created a desktop application (WinForms or WPF) the App.config file is automatically copied to the output folder alongside with the executable and renamed to YourApplication.exe.config. It is inside this file that you could have the <appSettings> section:
<configuration>
<appSettings>
<add key="exampleAppSetting" value="example app setting data"/>
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
and then you will be able to access this value like this:
var appSettings = System.Configuration.ConfigurationManager.AppSettings;
string value = appSettings["exampleAppSetting"];
You might prefer using custom configuration sections when you have some complex config properties. In this case it might make more sense to move them in a separate configuration file and write a custom section.

Configuration system failed to initialise

I have a console application with a config file called app.config. The full code behind by app.config file is as follows:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ClientSettingsProvider.ServiceUri" value=""/>
<add key="Server" value="0.0.0.0"/>
<add key="DB" value="Test"/>
<add key="UserName" value="testuser"/>
<add key="Password" value="testuser"/>
<add key="AgentEmail" value="test#gmail.com"/>
</appSettings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup>
</configuration>
When I try to run my application, I get an error : Configuration system failed to initialize. Any idea what am I doing wrong?
Remove the configSections from the file if you don't require it.
You're defining a section group and a contained section in your config here:
<configuration>
<configSections>
<sectionGroup name="applicationSettings"
type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="LeadDataEmail.Properties.Settings"
type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
That means, there must be a <applicationSettings> container, with a contained <LeadDataEmail.Properties.Settings> XML element in your <configuration>:
<configuration>
<configSections>
......
</configSections>
<applicationSettings>
<LeadDataEmail.Properties.Settings
attribute1="value1"
attribute2="value2" />
</applicationSettings>
....
</configuration>
but I don't see any trace of that in your config file - no wonder the config system cannot initialize!

Categories