c# Application Configuration File: AppSettings Reads Empty? - c#

This is my first time using an XML config file. In the solution explorer I right click, add, new item, application config. file.
I then edited the file to read...
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Key1" value="1000" />
</appSettings>
</configuration>
...and tried to access it with...
Int32.Parse(ConfigurationManager.AppSettings.Get("Key1"));
...but it says that the parameter is null. I looked at just ConfigurationManager.AppSettings and it's AllKeys property has dimension 0.
What am I doing wrong?
Thanks!

Right-click on your project, choose Properties>Settings tab and edit your settings there because the config file is not the only place these values are stored at.
In your code use Settings.Default.MySetting to access the settings.
You'll need to add using MyProjectName.Properties; to your using statements in order to access the settings this way or you'll have to fully qualify it as MyProjectName.Properties.Settings.Default.MySetting...

I know this is super old but I just encountered this opening an old project. A reference to System.Configuration was missing.

To ensure get information from App.config using ConfigurationManager.AppSettings["<Key name>"]; be sure to set your values inside <appSettings> section.
Example:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<appSettings>
<add key ="IntervalSeconds" value ="60000"/>
<add key ="OutputPathLog" value ="\\myserver\hackingtrack\Projects\Log\"/>
<!--Jorgesys si Elenasys sunt puisori-->
<add key="InputFeeds1" value="https://cld.blahbla.com//portadaKick.json" />
<add key="InputFeeds2" value="https://cld.blahbla.com//portadaKick.json" />
<add key="InputFeeds3" value="https://cld.blahbla.com//portadaKick.json" />
</appSettings>
</configuration>
Retrieving values:
string intervalSeconds = ConfigurationManager.AppSettings["IntervalSeconds"];
string inputFeeds1 = ConfigurationManager.AppSettings["InputFeeds1"]; ;
string inputFeeds2 = ConfigurationManager.AppSettings["InputFeeds2"];
string inputFeeds3 = ConfigurationManager.AppSettings["InputFeeds3"];

Related

How do I overwrite the default settings value in the settings designer for my Connection String

I need to use a different connection string than the one in the default settings value in the settings designer in order to run on my staging PC.
I have in settings.designer.cs:
[global::System.Configuration.DefaultSettingValueAttribute("Data Source=MyServer\\MyDB;Initial Catalog=MyDB;Integrated Security=True;Pers" +
"ist Security Info=True")]
public string MyConnectionString {
get {
return ((string)(this["MyConnectionString"]));
}
}
My app.config is this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<clear />
<add name="MyConnectionString " connectionString=Data Source=MyServer2\\MyDB;Initial Catalog=MyDB;;Trusted_Connection=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
I want the application to use the settings in app.config but it persists in using the settings in the settings designer file.
I have tried various permutations of the following as well:
<add name="AppName.Properties.Settings.Default.MyConnectionString" connectionString=Data Source=MyServer2\\MyDB;Initial Catalog=MyDB;;Trusted_Connection=True"
providerName="System.Data.SqlClient" />
such as:
AppName.Properties.Settings.GlobalReference.Default.MyConnectionString
and:
ApplicationSettings.AppName.Properties.Settings.GlobalReference.Default.MyConnectionString
Any thoughts or ideas would be greatly appreciated.
In order for this to work, you have to have System.Configuration in your references.
you need to access the configuration Manager
System.Configuration.ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString;
change your connection string name to something more simple or you'll have to use all of that
System.Configuration.ConfigurationManager.ConnectionStrings["AppName.Properties.Settings.Default.MyConnectionString"].ConnectionString;
if you want to use system properties you should add the system.reflection reference

Why no AppSettings in my ConfigurationManager?

I don't know why but i don't have AppSettings in my app.config.file.
If i add it, when i run my apps, appSetting is deleted, so i'm unable to read my data !
Here is my file :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<add key="RepertoireEntree" value="E:\DEV\Autres\DevAgréga\Input\*.txt"/>
<add key="RepertoireSortie" value="E:\DEV\Autres\DevAgréga\Output\"/>
</configuration>
And in c# :
string RepertoireEntree = ConfigurationManager.AppSettings["RepertoireEntree"];
You have your app settings in a appSettings element, else it won't be recognized:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="RepertoireEntree" value="E:\DEV\Autres\DevAgréga\Input\*.txt"/>
<add key="RepertoireSortie" value="E:\DEV\Autres\DevAgréga\Output\"/>
</appSettings>
</configuration>
By the way, it is easier to use settings the usual way. You can do this by creating a settings file from your Project Settings > Settings tab.
Visual Studio will generate the XML elements in the app.config for you and you can reference your property like this:
string re = Properties.Settings.Default.RepertoireEntree;
You do not have your xml correct in the app.config file.
note the start and end tags for appSettings
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="RepertoireEntree" value="E:\DEV\Autres\DevAgréga\Input\*.txt"/>
<add key="RepertoireSortie" value="E:\DEV\Autres\DevAgréga\Output\"/>
</appSettings>
</configuration>
PS
While this is probably not an issue for you (but moreso for future readers)
Make sure you have this reference:
Namespace: System.Configuration
Assembly: System.Configuration (in System.Configuration.dll)
as noted on MSDN

How to change default Bucket in app.config

My App.Config looks like this.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="couchbaseClients">
<section name="couchbase"
type="Couchbase.Configuration.Client.Providers.CouchbaseClientSection, Couchbase.NetClient"/>
</sectionGroup>
</configSections>
<couchbaseClients>
<couchbase useSsl="false">
<servers>
<add uri="http://localhost:8091/pools"></add>
</servers>
<buckets>
<add name="CBMigration" useSsl="false">
<connectionPool name="custom" maxSize="10" minSize="5"></connectionPool>
</add>
</buckets>
</couchbase>
</couchbaseClients>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
</startup>
</configuration>
In that i given bucket name is "CBMigration" but still the entries are in default bucket only.
And my c# code for initializing cluster is _instance = new Cluster("couchbaseClients/couchbase");
I need to make the bucket as "CBMigration" for the Cluster i initialized using the app.config.
Where i am going wrong ?
Please help me...
I think there's a gap in documentation there. The bucket entries in are only used to provide customized defaults for the bucket's configuration. That is the use of ssl, connection pool tuning, etc...
But having just one bucket config entry like that doesn't actually change the behavior of OpenBucket(): the default bucket used by the client is always "default".
You still have to explicitly open the specific bucket you want, using OpenBucket(BucketName, BucketPassword)... It's just that once you do that, said bucket will be opened using tuning parameters found in its corresponding section in App.config instead of hardcoded default ones.
Does that make sense?

Reading settings from app.config in .net 4.5

I've added a reference to System.Configuration. I've created App1.config in my project and populated it with the following code:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ResistanceA" value="0.04"/>
<add key="ResistanceB" value="0.04"/>
<add key="ResistanceC" value="0.01"/>
<add key="TempBattLow" value="40"/>
<add key="TempBattHigh" value="45"/>
<add key="TempLoad" value="40"/>
</appSettings>
</configuration>
Then I try to read the values using the following code,
using System.Configuration;
string str = ConfigurationManager.AppSettings.Get("ResistanceA");
However I do not get the data. Any idea what I am doing wrong? Thanks.
Make sure the (app name here).config file actually appears in the same folder as your (app name here).exe file. Being that you called it App1.config, I'm guessing that you have more than one.
Visual Studio renames App.Config to the actual (app name here).config file during a build, not App1.config.

Updating .config file with data from the user

I am trying to save some settings to the appSettings section of my configuration file so I may use the data to carry out the processes of the program. On the click of a button I want the data coming from the user to be saved in the config file. The code I am using is:
private void button1_Click(object sender, EventArgs e)
{
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["key1"].Value = "value1";
config.AppSettings.Settings["key2"].Value = "value2";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
Before the code is executed my app.config file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<appSettings>
<add key="roshane" value=""/>
<add key="email" value=""/>
<add key="super" value=""/>
<add key="phone" value=""/>
</appSettings>
<connectionStrings>
<add name="AutoReportEmailerConnectionString"
connectionString="Data Source=roshane\sqlexpress;Initial Catalog=ICR_v5.0;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
</configuration>
After the code is execute the programName.exe.config file is the same as the app.config. Is there something I am missing why the values are not being added to the programName.exe.config file?
config.Save(ConfigurationSaveMode.Modified) works only when you modify an exisint key in other words a key that was in the web config before if you need to actually add key values to the web config just call config.Save() with no parameters
If you want to add new Key to config file, need to add it first in Settings collection:
config.AppSettings.Settings.Add("Key", "Value");
Then call Save method.

Categories