208

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?

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Matt
  • 8,195
  • 31
  • 115
  • 225

18 Answers18

410

This works for me:

string value = System.Configuration.ConfigurationManager.AppSettings[key];
Adam
  • 26,549
  • 8
  • 62
  • 79
  • 7
    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. – Adam May 26 '12 at 14:28
  • 45
    Require add reference `System.Configuration`. – checksum Dec 04 '14 at 08:54
  • But reference to System.Configuration must be added other wise application wouldn't compile saying that "ConfigurationManager" not found. – Venugopal M Dec 17 '14 at 07:14
  • 16
    My **.NET 4.5** `System.Configuration` have not `ConfigurationManager` – qwert_ukg Apr 04 '16 at 05:43
  • @qwert_ukg You don't need a 4.5 version. 4.0 version will work just fine with 4.5. Just include it in your References. – vapcguy Aug 09 '16 at 14:22
  • @Adam forgot you had to include in both projects `app.config` files in VS if you are using multiple projects... thanks – interesting-name-here Jun 27 '17 at 16:30
  • 5
    I'm also getting a null in a 4.5 project - spent two hours on this.. Has to be a bug. – IrishChieftain Jan 07 '19 at 17:59
  • 1
    I too am seeing this in a multi-target application, my .net core config works but the .net framework config does not (using ConfigurationManager) – Michael Brown Feb 12 '20 at 19:09
  • 1
    I solved by installing this nuget package: `System.Configuration.ConfigurationManager` and then: `string value = ConfigurationManager.AppSettings[key];` – alansiqueira27 Aug 30 '22 at 13:58
71

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"];
rotgers
  • 1,992
  • 1
  • 15
  • 25
  • 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). – Tim Jan 31 '17 at 12:20
  • This could do with explanding to cover where there is no "assemblies" tab (at least VS2019) – SomeoneElse Apr 23 '20 at 22:52
23

Give this a go:

string filePath = ConfigurationManager.AppSettings["ClientsFilePath"];
dtsg
  • 4,408
  • 4
  • 30
  • 40
  • 4
    Your implementation of it must be incorrect. This definitely works for retrieving key values from a config file. – dtsg May 26 '12 at 13:52
  • 1
    Make sure you add a reference to System.Configuration in the references for your project! – GrahamJ May 22 '19 at 14:07
22

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();
Martin Schneider
  • 14,263
  • 7
  • 55
  • 58
Masoud Siahkali
  • 5,100
  • 1
  • 29
  • 18
  • 4
    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. – The Dumb Radish Aug 09 '16 at 08:30
  • 2
    This worked for me as well. I was getting a `null` string with the above recommendations, but `Properties.Settings.Default.` worked like a charm! – dub stylee Feb 02 '17 at 00:52
  • @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: https://stackoverflow.com/questions/61018443/winforms-application-settings-changes-dont-appear-to-be-persisting?noredirect=1#comment107954751_61018443. Still haven't figured out why user-changed settings of those values don't persist... – marky Apr 05 '20 at 20:37
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

Kkloe
  • 189
  • 1
  • 8
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

Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
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)

Mike Dean
  • 67
  • 1
  • 3
  • 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. – Maytham Fahmi Aug 12 '19 at 07:54
2

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"];
Imran Ali Khan
  • 8,469
  • 16
  • 52
  • 77
Steve
  • 549
  • 6
  • 21
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 :   jack@google.com;thad@google.com;
Tom Stickel
  • 19,633
  • 6
  • 111
  • 113
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();
    }
suulisin
  • 1,414
  • 1
  • 10
  • 17
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"]

Leo
  • 398
  • 6
  • 11
2
ConfigurationManager.RefreshSection("appSettings")
string value = System.Configuration.ConfigurationManager.AppSettings[key];
musicinmusic
  • 247
  • 1
  • 11
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
1

You can simply type:

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

because key is an object and AppSettings takes a string

Sandeep Sukhija
  • 1,156
  • 16
  • 30
Soprano
  • 21
  • 9
1

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"];
    }
Stanley
  • 2,434
  • 18
  • 28
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.

BCA
  • 7,776
  • 3
  • 38
  • 53
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.

-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
bigtheo
  • 624
  • 9
  • 16