AppSettings get value from .config file
Asked Answered
G

18

212

I'm not able to access values in configuration file.

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var clientsFilePath = config.AppSettings.Settings["ClientsFilePath"].Value; 
// the second line gets a NullReferenceException

.config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <!-- ... -->
    <add key="ClientsFilePath" value="filepath"/>
    <!-- ... -->
  </appSettings>
</configuration>

Do you have any suggestion what should I do?

Gardenia answered 26/5, 2012 at 13:25 Comment(0)
L
414

This works for me:

string value = System.Configuration.ConfigurationManager.AppSettings[key];
Lactescent answered 26/5, 2012 at 13:30 Comment(9)
The code i provided requires YourProgram.exe.config file to exist in the same folder as YourProgram.exe. Just make sure its there. A common error is to copy app.config file to the destination directory, which will not work.Lactescent
Require add reference System.Configuration.Hairsplitting
But reference to System.Configuration must be added other wise application wouldn't compile saying that "ConfigurationManager" not found.Attachment
My .NET 4.5 System.Configuration have not ConfigurationManagerTracey
@Tracey You don't need a 4.5 version. 4.0 version will work just fine with 4.5. Just include it in your References.Lockjaw
@Lactescent forgot you had to include in both projects app.config files in VS if you are using multiple projects... thanksProceed
I'm also getting a null in a 4.5 project - spent two hours on this.. Has to be a bug.Edouard
I too am seeing this in a multi-target application, my .net core config works but the .net framework config does not (using ConfigurationManager)Absorption
I solved by installing this nuget package: System.Configuration.ConfigurationManager and then: string value = ConfigurationManager.AppSettings[key];Blinking
C
73

The answer that dtsg gave works:

string filePath = ConfigurationManager.AppSettings["ClientsFilePath"];

BUT, you need to add an assembly reference to

System.Configuration

Go to your Solution Explorer and right click on References and select Add reference. Select the Assemblies tab and search for Configuration.

Reference manager

Here is an example of my App.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <appSettings>
    <add key="AdminName" value="My Name"/>
    <add key="AdminEMail" value="MyEMailAddress"/>
  </appSettings>
</configuration>

Which you can get in the following way:

string adminName = ConfigurationManager.AppSettings["AdminName"];
Cinquefoil answered 20/3, 2015 at 13:15 Comment(2)
I seem to have the same issue as OP. Using VS2015. I don't know how or why, but my reference to System.Configuration says System.configuration (lower case).Bremen
This could do with explanding to cover where there is no "assemblies" tab (at least VS2019)Raymonderaymonds
A
23

Give this a go:

string filePath = ConfigurationManager.AppSettings["ClientsFilePath"];
Alford answered 26/5, 2012 at 13:28 Comment(2)
Your implementation of it must be incorrect. This definitely works for retrieving key values from a config file.Alford
Make sure you add a reference to System.Configuration in the references for your project!Saddletree
H
23

Read From Config :

You'll need to add a reference to Config

  1. Open "Properties" on your project
  2. Go to "Settings" Tab
  3. Add "Name" and "Value"
  4. Get Value with using following code :
string value = Properties.Settings.Default.keyname;

Save to Config :

Properties.Settings.Default.keyName = value;
Properties.Settings.Default.Save();
Highjack answered 7/8, 2016 at 12:34 Comment(3)
Really helpful as all the other answers using ConfigurationManager do not work if you add your values in the Settings tabs of the project properties as you have described. Thanks.Maremma
This worked for me as well. I was getting a null string with the above recommendations, but Properties.Settings.Default.<keyName> worked like a charm!Pluvious
@Masoud Siahkali, Last week I tried pretty much what you have here in my own project, but the values, when changed by the user at run time (Just running it from the VS GUI for now) do not persist across instances. My question: #61018943. Still haven't figured out why user-changed settings of those values don't persist...Congresswoman
K
8

I am using:

    ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
    //configMap.ExeConfigFilename = @"d:\test\justAConfigFile.config.whateverYouLikeExtension";
    configMap.ExeConfigFilename = AppDomain.CurrentDomain.BaseDirectory + ServiceConstants.FILE_SETTING;
    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
    value1 = System.Configuration.ConfigurationManager.AppSettings["NewKey0"];
    value2 = config.AppSettings.Settings["NewKey0"].Value;
    value3 = ConfigurationManager.AppSettings["NewKey0"];

Where value1 = ... and value3 = ... gives null and value2 = ... works

Then I decided to replace the internal app.config with:

// Note works in service but not in wpf
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", @"d:\test\justAConfigFile.config.whateverYouLikeExtension");
ConfigurationManager.RefreshSection("appSettings");

string value = ConfigurationManager.AppSettings["NewKey0"];

Using VS2012 .net 4

Kindly answered 30/4, 2014 at 6:54 Comment(1)
This is exactly what i needed. Really helpful, thanks.Yahweh
R
6

In the app/web.config file set the following configuration:

<configuration>
  <appSettings>
    <add key="NameForTheKey" value="ValueForThisKey" />
    ... 
    ...    
  </appSettings>
...
...
</configuration>

then you can access this in your code by putting in this line:

string myVar = System.Configuration.ConfigurationManager.AppSettings["NameForTheKey"];

*Note that this work fine for .net4.5.x and .net4.6.x; but do not work for .net core. Best regards: Rafael

Ruffina answered 23/2, 2017 at 14:30 Comment(0)
C
3

See I did what I thought was the obvious thing was:

string filePath = ConfigurationManager.AppSettings.GetValues("ClientsFilePath").ToString();

While that compiles it always returns null.

This however (from above) works:

string filePath = ConfigurationManager.AppSettings["ClientsFilePath"];
Chorus answered 1/6, 2015 at 15:34 Comment(0)
C
3

Coming back to this one after a long time...

Given the demise of ConfigurationManager, for anyone still looking for an answer to this try (for example):

AppSettingsReader appsettingsreader = new AppSettingsReader();
string timeAsString = (string)(new AppSettingsReader().GetValue("Service.Instance.Trigger.Time", typeof(string)));

Requires System.Configuration of course.

(Editted the code to something that actually works and is simpler to read)

Canica answered 30/4, 2018 at 11:20 Comment(1)
Good answer, but please clean up, why create new instance of AppSettingsReader when you re-creating AppSettingsReader again, and you do not need to cast string, you can just end it to .ToString() override.Capua
K
2

Some of the Answers seems a little bit off IMO Here is my take circa 2016

<add key="ClientsFilePath" value="filepath"/>

Make sure System.Configuration is referenced.

Question is asking for value of an appsettings key

Which most certainly SHOULD be

  string yourKeyValue = ConfigurationManager.AppSettings["ClientsFilePath"]

  //yourKeyValue should hold on the HEAP  "filepath"

Here is a twist in which you can group together values ( not for this question)

var emails = ConfigurationManager.AppSettings[ConfigurationManager.AppSettings["Environment"] + "_Emails"];

emails will be value of Environment Key + "_Emails"

example :   [email protected];[email protected];
Kathiekathleen answered 2/6, 2016 at 21:42 Comment(0)
I
2

For web application, i normally will write this method and just call it with the key.

private String GetConfigValue(String key)
    {
       return System.Web.Configuration.WebConfigurationManager.AppSettings[key].ToString();
    }
Idolism answered 15/5, 2017 at 8:30 Comment(0)
B
2
  1. Open "Properties" on your project
  2. Go to "Settings" Tab
  3. Add "Name" and "Value"

CODE WILL BE GENERATED AUTOMATICALLY

    <configuration>
      <configSections>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup ..." ... >
          <section name="XX....Properties.Settings" type="System.Configuration.ClientSettingsSection ..." ... />
        </sectionGroup>
      </configSections>
      <applicationSettings>
        <XX....Properties.Settings>
          <setting name="name" serializeAs="String">
            <value>value</value>
          </setting>
          <setting name="name2" serializeAs="String">
            <value>value2</value>
          </setting>
       </XX....Properties.Settings>
      </applicationSettings>
    </configuration>

To get a value

Properties.Settings.Default.Name

OR

Properties.Settings.Default["name"]

Boar answered 9/4, 2019 at 13:0 Comment(0)
A
2
ConfigurationManager.RefreshSection("appSettings")
string value = System.Configuration.ConfigurationManager.AppSettings[key];
Anglo answered 3/6, 2019 at 17:37 Comment(0)
S
2

Or you can either use

string value = system.configuration.ConfigurationManager.AppSettings.Get("ClientsFilePath");

//Gets the values associated with the specified key from the System.Collections.Specialized.NameValueCollection
Slovene answered 11/10, 2019 at 11:11 Comment(0)
H
2

Updated

ConfigurationManager is outdated, you need to use IConfiguration in the .NET Сore environment (IConfiguration is provided by .NET Core built-in dependency injection).

    private readonly IConfiguration config;

    public MyConstructor(IConfiguration config)
    {
        this.config = config;
    }
    public void DoSomethingFunction()
    {
        string settings1 = config["Setting1"];
    }
Hemphill answered 13/12, 2021 at 15:25 Comment(0)
G
1

You can simply type:

string filePath = Sysem.Configuration.ConfigurationManager.AppSettings[key.ToString()];

because key is an object and AppSettings takes a string

Gorman answered 14/11, 2017 at 8:47 Comment(0)
B
0

My simple test also failed, following the advice of the other answers here--until I realized that the config file that I added to my desktop application was given the name "App1.config". I renamed it to "App.config" and everything immediately worked as it ought.

Breastsummer answered 29/8, 2014 at 19:11 Comment(0)
I
0

In my case I had to throw a ' on either side of the '@System.Configuration.ConfigurationManager.AppSettings["key"]' for it to be read into my program as a string. I am using Javascript, so this was in my tags. Note: ToString() was not working for me.

Interlude answered 31/8, 2022 at 19:2 Comment(0)
D
-1

Do something like this :

string value1 = System.Configuration.ConfigurationManager.AppSettings.Get(0); //for the first key


string value2 = System.Configuration.ConfigurationManager.AppSettings.Get(1); //for the first key
Dissatisfied answered 29/9, 2022 at 17:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.