ConfigurationManager.AppSettings[key] is always null - c#

I am trying to get the value for the key "sUser" in appSetting section from app.config
this is the code on my class.cs
string sUsr = ConfigurationManager.AppSettings.Get["sUser"];
But always its null.
I try this code (I took it from MSDN):
// Get the configuration file.
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Get the appSettings section.
AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");
// Get the auxiliary file name.
Console.WriteLine("Auxiliary file: {0}", config.AppSettings.File);
But it shows that the file Empty
Also I am using the stting console to write those properties and it works if I get the apps using
string sUsr = WIW.Business.Properties.Settings.Default.sUser;
But I am going to use that class as a reference in a website and on the web.config of the site I can't configure those settings

In your App.config the appSettings section should look like the following:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="sUser" value="Test"/>
</appSettings>
</configuration>

use Properties.Settings.Default.{your_setting_key} to access the value
I.E
Properties.Settings.Default.sPassword return 8909039388
All these were included in Properties Class.

I had the same problem. I was calling another project(In the same solution) and was expecting the appSettings to be present.
To make it work,I added the following lines in the application that was calling the target application.
<appSettings>
<add key="sUser" value="Test"/>
</appSettings>
It worked for me after that. Try this. It might help you too

Here its my app.config, if I try to get the key values from the appSettings sections I always get null, but If I try to get them from applicationsection Its no problem, the thing is that I need put that applicationsection on a web site but on a web site i can put applicationSettings
<configuration>
<appSettings>
<add key="sUser" value="userbancolombia">
<add key="sPassword" value="8909039388">
<appSettings>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="WIW.Business.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<system.serviceModel>
<bindings />
<client />
</system.serviceModel>
<applicationSettings>
<WIW.Business.Properties.Settings>
<setting name="WIW_Business_WsCCMain_ConsultaNuips" serializeAs="String">
<value>http://coomeva1/AsisaWS_2008/ConsultaNuips.asmx</value>
</setting>
<setting name="WIW_Business_WsCCAux_ConsultaNuips" serializeAs="String">
<value>http://coomeva1/AsisaWS_2008_Sec/ConsultaNuips.asmx</value>
</setting>
<setting name="WIW_Business_WsCEMain_ConsultaCedulaExtranjeria"
serializeAs="String">
<value>http://coomeva1/AsisaWS_2008/ConsultaCedulaExtranjeria.asmx</value>
</setting>
<setting name="WIW_Business_WsCEAux_ConsultaCedulaExtranjeria"
serializeAs="String">
<value>http://coomeva1/AsisaWS_2008_Sec/ConsultaCedulaExtranjeria.asmx</value>
</setting>
<setting name="sUser" serializeAs="String">
<value>userbancolombia</value>
</setting>
<setting name="sPassword" serializeAs="String">
<value>8909039388</value>
</setting>
</WIW.Business.Properties.Settings>
</applicationSettings>
</configuration>

Related

configurable value to Web Reference C#

i am confuse about this problem. I have a app.config and a web reference but my app.config url value thus not affect my web reference or the web reference url not change from uat process to prod process.
here is my 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="AFM_SA5.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>
<AFM_SA5.Properties.Settings>
<setting name="AFM_SA5_WebReference_TxnService" serializeAs="String">
<value>http://10.81.120.33:8181/FEATS/TxnService.asmx</value>
</setting>
</AFM_SA5.Properties.Settings>
</applicationSettings>
</configuration>
and here is my reference.cs
public TxnService() {
this.Url = global::AFM_SA5.Properties.Settings.Default.AFM_SA5_WebReference_TxnService;
if ((this.IsLocalFileSystemWebService(this.Url) == true)) {
this.UseDefaultCredentials = true;
this.useDefaultCredentialsSetExplicitly = false;
}
else {
this.useDefaultCredentialsSetExplicitly = true;
}
}
and my settings.settings
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="AFM_SA5.Properties" GeneratedClassName="Settings">
<Profiles />
<Settings>
<Setting Name="AFM_SA5_WebReference_TxnService" Type="(Web Service URL)" Scope="Application">
<Value Profile="(Default)">http://ph-sliderinsite.wdc.com:8181/FEATS/TxnService.asmx</Value>
</Setting>
</Settings>
</SettingsFile>
Based on your description, you want to your app.config.value affect the web reference url
value.
You need to note the following bold code should be your current project name.
After setting it, if you change the value in app.config and open the Setting.settings, you
will get a message box that ask if you need to change the value in Settings.settings.
Finally, click the yes, the value will be changed.

I can't get data from my App.config

I'm trying to get data from my App.config and searching about I have found up to 4 ways to get that data, but basically you should use
ConfigurationManager.AppSettings["NameKey/NameSetting"];
My App.config code is
<?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="DXThemeManager" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="InterfazPrueba1.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<DXThemeManager>
<setting name="ApplicationThemeName" serializeAs="String">
<value>Office2016White</value>
</setting>
</DXThemeManager>
</userSettings>
<applicationSettings>
<InterfazPrueba1.Properties.Settings>
<setting name="HostBD" serializeAs="String">
<value>LOCALHOST</value>
</setting>
<setting name="NombreBD" serializeAs="String">
<value>Pruebas1</value>
</setting>
<setting name="ServerBD" serializeAs="String">
<value>DESKTOP-O037RKH</value>
</setting>
<setting name="InstanceBD" serializeAs="String">
<value />
</setting>
<setting name="UsuarioBD" serializeAs="String">
<value>sa</value>
</setting>
<setting name="PassBD" serializeAs="String">
<value>123</value>
</setting>
</InterfazPrueba1.Properties.Settings>
</applicationSettings>
</configuration>
And the code in my class is:
private void datosConexion()
{
server = ConfigurationManager.AppSettings["ServerBD"];
user = ConfigurationManager.AppSettings["UsuarioBD"];
pass = ConfigurationManager.AppSettings["PasswordBD"];
host = ConfigurationManager.AppSettings["HostBD"];
db= ConfigurationManager.AppSettings["NombreBD"];
instance = ConfigurationManager.AppSettings["InstanceBD"];
Console.WriteLine("Datos:"+server + user + pass + host + db + instance);
}
All the variables have nothing.
I've tried all the ways I've seen and changed the values to keys but I just can retrieve the data...
Any idea about what is wrong or what am I doing bad?
Thank you for all the support you could give me.
ConfigurationManager.AppSettings["NameSetting"] retrives a setting that is defined in the App.config like this:
<configuration>
<configSections>
...
</configSections>
<userSettings>
...
</userSettings>
<appSettings>
<add key="NameSetting" value="123" />
</appSettings>
</configuration>
If you add project specific settings under Project->Properties->Settings you can access these through a class that gets generated for you:
string setting = InterfazPrueba1.Properties.Settings.Default.HostBD;

Application settings reset when exe changes location [duplicate]

This question already has answers here:
Settings.settings File Keeps Getting Reset
(4 answers)
Closed 6 years ago.
Hi I'm using the Visual Studio config files, however the settings change every time I move the exe.
How can I fix this?
app.config
<?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="GUIChangerUI.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<userSettings>
<GUIChangerUI.Properties.Settings>
<setting name="StarmadePath" serializeAs="String">
<value>default</value>
</setting>
<setting name="GuiPath" serializeAs="String">
<value>Not selected yet.</value>
</setting>
<setting name="FirstStart" serializeAs="String">
<value>True</value>
</setting>
<setting name="jpeg" serializeAs="String">
<value>default</value>
</setting>
<setting name="debug" serializeAs="String">
<value>default</value>
</setting>
<setting name="Darktheme" serializeAs="String">
<value>False</value>
</setting>
<setting name="Lightheme" serializeAs="String">
<value>True</value>
</setting>
<setting name="starmadeStarter" serializeAs="String">
<value />
</setting>
<setting name="_starmadeStarter" serializeAs="String">
<value />
</setting>
<setting name="OSMTheme" serializeAs="String">
<value>False</value>
</setting>
</GUIChangerUI.Properties.Settings>
</userSettings>
</configuration>
The actual configuration file containing saved configuration settings is stored here:
%APPDATA%\Local\<application name>\<application name>.<eid>_<hash>\<version>
According to this MSDN article::
<eid> is the URL, StrongName, or Path, based on the evidence available to hash.
<hash> is a SHA1 hash of evidence gathered from the CurrentDomain, in the following order of preference:
StrongName
URL
If neither of these is available, use the .exe path.
(my emphasis)
So the solution seems simple:
Create a strong name and sign your executable.
Then you will get the same unique hash every time and it won't change whenever you start the executable from a new location.
If you need help signing your application, please refer to this MSDN article: How to: Sign an Assembly with a Strong Name.
The user settings will be stored in your user's profile in such a way that the location of your application is linked. That's why the application, when moved, does not find the settings anymore.
What you can try to do is:
Create a new user setting named SettingsUpgradeRequired and set it to true in the settings designer in Visual Studio.
In your application's startup code, check whether SettingsUpgradeRequired is true and if so, perform a settings upgrade.
As the new setting will only be true after the settings file was reset, the following should import the old settings, and it should do so only once:
if (Properties.Settings.Default.SettingsUpgradeRequired)
{
try
{
Properties.Settings.Default.Upgrade();
Properties.Settings.Default.SettingsUpgradeRequired = false;
Properties.Settings.Default.Save();
}
catch (...)
{
... // Upgrade failed - tell the user or whatever
}
}
That behavior is by design because you could have multiple versions of you application (for instance a QA version, a PROD version and so on) that requires different setting storages. See also Client Settings FAQ for details.
If you need a settings management that is independend of the location / version of you app, i would suggest wo create your own settings file and store them below "%appdata%[company][application]"

Changing section name in app.config - causes ConfigurationException

I have a WinForms application that I have changed the name of. I've changed the name everywhere I can find it, and can find no traces of the old name (except as below) and everything works fine; the one exception is in app.config, where if I change OLDNAME to NEWNAME any attempt to read any of the configuration settings throws a ConfigurationExceptioon of "Configuration system not ready", if I recall correctly.
Can anyone suggest how I can change the OLDNAME below to something else, such as my new name, without upsetting the config system?
<?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="OLDNAME.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<OLDNAME.Properties.Settings>
<setting name="MainWindowPosition" serializeAs="String">
<value>0, 0, 0, 0</value>
</setting>
<setting name="UseShortDeviceNames" serializeAs="String">
<value>False</value>
</setting>
</OLDNAME.Properties.Settings>
</userSettings>
</configuration>
The link http://www.codeproject.com/Articles/10981/Understanding-Section-Handlers-App-config-File will explain more using Section Handlers for config.
You must change alsow the section name, you section name is linked to the projects where is build and you have two posibility:
- rename the project (output) and in app.config
- create a new custom group and use the settings

Save and reload app.config(applicationSettings) at runtime

I've stored configuration of my application in the app.config, by Visual Studio I've created some application key on the settings tab of project properties dialog, then I've set this key at application level(NOT at user level).
Visual Studio automatically generate the following xml file (app.config) :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="AleTest.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<AleTest.Properties.Settings>
<setting name="DatabasePath" serializeAs="String">
<value>Test.s3db</value>
</setting>
<setting name="DatabaseUser" serializeAs="String">
<value />
</setting>
<setting name="DatabasePass" serializeAs="String">
<value />
</setting>
</AleTest.Properties.Settings>
</applicationSettings>
</configuration>
Now I want to save and reload the settings at runtime, here's my code that allow to save the value DatabasePath in the configuration file:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSectionGroup applicationSectionGroup = config.GetSectionGroup("applicationSettings");
ConfigurationSection applicationConfigSection = applicationSectionGroup.Sections["AleTest.Properties.Settings"];
ClientSettingsSection clientSection = (ClientSettingsSection)applicationConfigSection;
//Database Configuration Setting
SettingElement applicationSetting = clientSection.Settings.Get("DatabasePath");
applicationSetting.Value.ValueXml.InnerXml = this.textBoxPath.Text.Trim();
applicationConfigSection.SectionInformation.ForceSave = true;
config.Save();
The problem is that with this code the new settings aren't loaded by application until I restart the application; is there a way to reload the config settings at runtime?
I also want to replace the fixed value of the name of applicationSettings section (AleTest.Properties.Settings) with a variable value, exist a variable in the framework the assume this value (AleTest.Properties.Settings) ?
You need to make a call to ConfigurationManager.RefreshSection in order to have the values re-read from disk.
I did a some tests and here is result.
For auto generated class Settings the call of ConfigurationManager.RefreshSection("applicationSettings"); doesn't apply the modified values for members marked with ApplicationScopedSettingAttribute, it applies the changes to future calls via ConfigurationManager members (and not sure about UserScopedSettingAttribute).
Instead call Settings.Default.Reload();
What you want is accomplish able by creating an custom ConfigSection which allows you more control and allows you to change the name. Configuration manager has a refresh section which will allow you reload the data.
Aleroot's code for updating values worked fine.
In spite of Properties.Settings being write only (no set).
To refresh, this worked for me:
ConfigurationManager.RefreshSection("applicationSettings");
But I'm using this to access the parameter:
string test = Properties.Settings.Default.MyString;
MessageBox.Show("Paramètres/Settings MyString = " + test);

Categories