951

I'm working on a C# class library that needs to be able to read settings from the web.config or app.config file (depending on whether the DLL is referenced from an ASP.NET web application or a Windows Forms application).

I've found that

ConfigurationSettings.AppSettings.Get("MySetting")

works, but that code has been marked as deprecated by Microsoft.

I've read that I should be using:

ConfigurationManager.AppSettings["MySetting"]

However, the System.Configuration.ConfigurationManager class doesn't seem to be available from a C# Class Library project.

What is the best way to do this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Russ Clark
  • 13,260
  • 16
  • 56
  • 81
  • 63
    Like i read 4 MSDN examples and articles.. And landed up here. Just add a reference.. why can't they just say that. Good question! +1 – Piotr Kula Sep 14 '12 at 10:18
  • 1
    If you want to **write the settings back** as well, look **[here](https://stackoverflow.com/a/11841175/1016343)** how you can do it. – Matt Jul 17 '17 at 11:16
  • 1
    Possible duplicate of [Pros and cons of AppSettings vs applicationSettings (.NET app.config / Web.config)](https://stackoverflow.com/questions/460935/pros-and-cons-of-appsettings-vs-applicationsettings-net-app-config-web-confi) – Matt Jul 17 '17 at 11:17

28 Answers28

1032

For a sample app.config file like below:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="countoffiles" value="7" />
    <add key="logfilelocation" value="abc.txt" />
  </appSettings>
</configuration>

You read the above application settings using the code shown below:

using System.Configuration;

You may also need to also add a reference to System.Configuration in your project if there isn't one already. You can then access the values like so:

string configvalue1 = ConfigurationManager.AppSettings["countoffiles"];
string configvalue2 = ConfigurationManager.AppSettings["logfilelocation"];
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ram
  • 15,908
  • 4
  • 48
  • 41
  • 154
    I like your answer more than the accepted answer. Answers with examples always do the trick for me. – Brendan Vogt Feb 04 '14 at 07:36
  • @Gigo I guess because it answers questions of people who visit this question (and they may not care about OP's one :)) – Spook May 17 '16 at 07:07
  • @Gigo, it says "You may also need to also add a reference to System.Configuration in your project if there isn't one already." -- That specifically answers the OP's question. Though it's kind of glossed over if you ask me. – BrainSlugs83 Sep 18 '16 at 05:58
  • @NightmareGames that's because you didn't add the reference like the answer said to do. If you use `ConfigurationSettings` instead of `ConfigurationManager` then you *are* using an obsolete API. That's the whole point. – BrainSlugs83 Sep 18 '16 at 05:59
  • 2
    Can someone tell me why they think System.Configuration is not added by default... this seems like a pretty basic need in most applications. – Todd Vance Apr 26 '17 at 17:53
  • This answer, which gives full source code inclusive of the App.Config section (thank you) helped me solve a WCF problem, which has been vexing me. It turns out that my application does not see the App.config file. This answer helped me isolate the cause easily with no research required on implementing reading AppSettings. – Sarah Weinberger Aug 15 '18 at 14:29
  • "You may also need to also add a reference to System.Configuration in your project if there isn't one already." Oh you have got to be kidding me. – Andrew Keeton Mar 22 '20 at 23:49
  • adding a reference to System.Configuration in your project is not working on Mac – Dmitry Grinko Jul 26 '22 at 22:18
889

You'll need to add a reference to System.Configuration in your project's references folder.

You should definitely be using the ConfigurationManager over the obsolete ConfigurationSettings.

DrBeco
  • 11,237
  • 9
  • 59
  • 76
womp
  • 115,835
  • 26
  • 236
  • 269
  • 4
    Is this still accurate for .net core. – Triynko Mar 05 '20 at 19:52
  • @Triynko You should specify the .NET Core version you have in mind to confirm compatibility, because at this point in time as of this writing.. your looking at .NET Core 3.1, .NET 5 or 6. Also, those reading.. For the note, C# 9 and VS2019 - Program.cs does not need a reference to System.Configuration (unnecessary). – WiiLF Dec 07 '21 at 05:08
110

Update for .NET Framework 4.5 and 4.6; the following will no longer work:

string keyvalue = System.Configuration.ConfigurationManager.AppSettings["keyname"];

Now access the Setting class via Properties:

string keyvalue = Properties.Settings.Default.keyname;

See Managing Application Settings for more information.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
bsivel
  • 2,821
  • 5
  • 25
  • 32
  • 2
    Properties since [2010](https://msdn.microsoft.com/library/a65txexh(v=vs.100).aspx]). – Nick Westgate Feb 19 '16 at 03:32
  • 2
    Thanks so much for posting this. I determined that Properties.Settings.Default.MachName worked, but I couldn't figure out why ConfigurationManager.AppSettings["MachName"] returned null. – J. Chris Compton May 20 '16 at 21:36
  • 2
    This ended my prolonged agony. Thanks. The framework should warn you that the old way is obsolete. – Neil B Nov 28 '17 at 11:55
  • 15
    Can't confirm. The ConfigurationManager.AppSettings["someKey"] works in .NET 4.5, 4.6, 4.7.1 – Ivanhoe Jun 05 '18 at 12:48
  • 1
    @Ivanhoe What version of VisualStudio did you use? The ConfigurationManager.AppSettings["someKey"] worked with 4.6.1 and VS 15.8.2 but failed with 4.6.1 and VS 15.9.2 for me. – kkuilla Nov 23 '18 at 13:34
  • 1
    _This is the method_ with VS2019 16.4.2 targeting .NET 4.5. Spent ½ day figuring out why `ConfigurationManager.AppSettings` returned an empty collection. – Gustav Jan 20 '20 at 15:09
  • 1
    Is this really correct? The updated docs can be found here, and they do not mention that? https://learn.microsoft.com/en-us/dotnet/api/system.configuration.configurationmanager.appsettings?view=netframework-4.8 – Johny Skovdal Jan 22 '20 at 07:39
  • 1
    I don't believe this is correct. Using VS2019 16.6.5 targeting .NET 4.8, `ConfigurationManager.AppSettings["key"]` works as expected. – Mmm Jul 28 '20 at 19:59
  • 2
    Not working on vs2022, this is a very outdated answer – OKEEngine Aug 03 '22 at 10:14
40

Right click on your class library, and choose the "Add References" option from the Menu.

And from the .NET tab, select System.Configuration. This would include the System.Configuration DLL file into your project.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shiva
  • 1,379
  • 1
  • 15
  • 32
  • After adding reference, was able to do `ConfigurationManager.ConnectionStrings[0].ConnectionString` – SushiGuy Dec 20 '17 at 20:41
30

I'm using this, and it works well for me:

textBox1.Text = ConfigurationManager.AppSettings["Name"];
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pagey
  • 549
  • 4
  • 2
  • 50
    The TS explicitly states, that he uses the same code, but his project fails to compile (due to missing references, as it turned out). -1 for not reading the question. – Isantipov Mar 12 '13 at 17:28
29

Read From Config:

You'll need to add a reference to the configuration:

  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 the configuration:

   Properties.Settings.Default.keyName = value;
   Properties.Settings.Default.Save();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Masoud Siahkali
  • 5,100
  • 1
  • 29
  • 18
  • 1
    FYI: Google likes your answer best. Shows up verbatim when you search for "get app config settings c#" – Steve Dec 16 '16 at 19:46
22

You must add a reference to the System.Configuration assembly to the project.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Otávio Décio
  • 73,752
  • 17
  • 161
  • 228
22

You might be adding the App.config file to a DLL file. App.Config works only for executable projects, since all the DLL files take the configuration from the configuration file for the EXE file being executed.

Let's say you have two projects in your solution:

  • SomeDll
  • SomeExe

Your problem might be related to the fact that you're including the app.config file to SomeDLL and not SomeExe. SomeDll is able to read the configuration from the SomeExe project.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Victor Naranjo
  • 221
  • 2
  • 2
14

Try this:

string keyvalue = System.Configuration.ConfigurationManager.AppSettings["keyname"];

In the web.config file this should be the next structure:

<configuration>
<appSettings>
<add key="keyname" value="keyvalue" />
</appSettings>
</configuration>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ruslan
  • 177
  • 1
  • 7
11

Step 1: Right-click on references tab to add reference.

Step 2: Click on Assemblies tab

Step 3: Search for 'System.Configuration'

Step 4: Click OK.

Then it will work.

 string value = System.Configuration.ConfigurationManager.AppSettings["keyname"];
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jitendra Suthar
  • 2,111
  • 2
  • 16
  • 22
8

I had the same problem. Just read them this way: System.Configuration.ConfigurationSettings.AppSettings["MySetting"]

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tom
  • 679
  • 1
  • 12
  • 29
  • 4
    As per Microsoft regarding ConfigurationSettings.AppSettings `This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings` – Peter M Feb 20 '14 at 13:44
  • 3
    this method is Obsolete – GabrielBB Aug 20 '14 at 16:50
7

As I found the best approach to access application settings variables in a systematic way by making a wrapper class over System.Configuration as below

public class BaseConfiguration
{
    protected static object GetAppSetting(Type expectedType, string key)
    {
        string value = ConfigurationManager.AppSettings.Get(key);
        try
        {
            if (expectedType == typeof(int))
                return int.Parse(value);
            if (expectedType == typeof(string))
                return value;

            throw new Exception("Type not supported.");
        }
        catch (Exception ex)
        {
            throw new Exception(string.Format("Config key:{0} was expected to be of type {1} but was not.",
                key, expectedType), ex);
        }
    }
}

Now we can access needed settings variables by hard coded names using another class as below:

public class ConfigurationSettings:BaseConfiguration
{
    #region App setting

    public static string ApplicationName
    {
        get { return (string)GetAppSetting(typeof(string), "ApplicationName"); }
    }

    public static string MailBccAddress
    {
        get { return (string)GetAppSetting(typeof(string), "MailBccAddress"); }
    }

    public static string DefaultConnection
    {
        get { return (string)GetAppSetting(typeof(string), "DefaultConnection"); }
    }

    #endregion App setting

    #region global setting


    #endregion global setting
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ashwini Jindal
  • 811
  • 8
  • 15
7

web.config is used with web applications. web.config by default has several configurations required for the web application. You can have a web.config for each folder under your web application.

app.config is used for Windows applications. When you build the application in Visual Studio, it will be automatically renamed to <appname>.exe.config and this file has to be delivered along with your application.

You can use the same method to call the app settings values from both configuration files: System.Configuration.ConfigurationSettings.AppSettings["Key"]

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • It's also possible to use ```System.Configuration.COnfigurationSettings.AppSettings.Get("Key")``` instead of using the square brackets. – Mason Dec 19 '17 at 09:24
6

Also, you can use Formo:

Configuration:

<appSettings>
    <add key="RetryAttempts" value="5" />
    <add key="ApplicationBuildDate" value="11/4/1999 6:23 AM" />
</appSettings>

Code:

dynamic config = new Configuration();
var retryAttempts1 = config.RetryAttempts;                 // Returns 5 as a string
var retryAttempts2 = config.RetryAttempts(10);             // Returns 5 if found in config, else 10
var retryAttempts3 = config.RetryAttempts(userInput, 10);  // Returns 5 if it exists in config, else userInput if not null, else 10
var appBuildDate = config.ApplicationBuildDate<DateTime>();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pomber
  • 23,132
  • 10
  • 81
  • 94
5

If your needing/wanting to use the ConfigurationManager class...

You may need to load System.Configuration.ConfigurationManager by Microsoft via NuGet Package Manager

Tools->NuGet Package Manager->Manage NuGet Packages for Solution...

Microsoft Docs

One thing worth noting from the docs...

If your application needs read-only access to its own configuration, we recommend that you use the GetSection(String) method. This method provides access to the cached configuration values for the current application, which has better performance than the Configuration class.

Chris Catignani
  • 5,040
  • 16
  • 42
  • 49
4

I strongly recommend you to create a wrapper for this call. Something like a ConfigurationReaderService and use dependency injection to get this class. This way you will be able to isolate this configuration files for test purposes.

So use the ConfigurationManager.AppSettings["something"]; suggested and return this value. With this method you can create some kind of default return if there isn't any key available in the .config file.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Custodio
  • 8,594
  • 15
  • 80
  • 115
  • 4
    Microsoft already has a bulit-in way to manage multiple versions of the same config file: [build configurations](https://msdn.microsoft.com/en-us/library/kkz9kefa.aspx), which allow having separate config files for each build configuration: `app.DEBUG.config`, `app.RELEASE.config`, and `app.TEST.config`, etc. – jpaugh Jun 13 '17 at 16:43
3

Just for completeness, there's another option available for web projects only: System.Web.Configuration.WebConfigurationManager.AppSettings["MySetting"]

The benefit of this is that it doesn't require an extra reference to be added, so it may be preferable for some people.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
rdans
  • 2,179
  • 22
  • 32
2

I always create an IConfig interface with typesafe properties declared for all configuration values. A Config implementation class then wraps the calls to System.Configuration. All your System.Configuration calls are now in one place, and it is so much easier and cleaner to maintain and track which fields are being used and declare their default values. I write a set of private helper methods to read and parse common data types.

Using an IoC framework you can access the IConfig fields anywhere your in application by simply passing the interface to a class constructor. You're also then able to create mock implementations of the IConfig interface in your unit tests so you can now test various configuration values and value combinations without needing to touch your App.config or Web.config file.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tony O'Hagan
  • 21,638
  • 3
  • 67
  • 78
2

Please check the .NET version you are working on. It should be higher than 4. And you have to add the System.Configuration system library to your application.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nayanajith
  • 605
  • 10
  • 15
  • 4
    This question was asked over 9 years ago, and already has over 20 answers, including 2 which each have over 600 upvotes, the accepted answer is to add a reference to System.Configuration. This additional answer does not add value. At best, this should be a comment on the accepted answer. – Richardissimo Sep 23 '18 at 06:17
  • Re *"higher than 4"*: In major version number? Or do you mean *"higher than 4.0"*? Or in other words, what side would [.NET Framework 4.5](https://en.wikipedia.org/wiki/.NET_Framework_version_history#.NET_Framework_4.5) be on? – Peter Mortensen Dec 27 '19 at 16:03
2

You can use the below line. In my case it was working: System.Configuration.ConfigurationSettings.AppSettings["yourKeyName"]

You must take care that the above line of code is also the old version and it's deprecated in new libraries.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mohammad D
  • 23
  • 5
2

The ConfigurationManager is not what you need to access your own settings.

To do this you should use

{YourAppName}.Properties.Settings.{settingName}

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
martin c
  • 29
  • 1
2

I was able to get the below approach working for .NET Core projects:

Steps:

  1. Create an appsettings.json (format given below) in your project.
  2. Next create a configuration class. The format is provided below.
  3. I have created a Login() method to show the usage of the Configuration Class.

    Create appsettings.json in your project with content:

    {
      "Environments": {
        "QA": {
          "Url": "somevalue",
     "Username": "someuser",
          "Password": "somepwd"
      },
      "BrowserConfig": {
        "Browser": "Chrome",
        "Headless": "true"
      },
      "EnvironmentSelected": {
        "Environment": "QA"
      }
    }
    
    public static class Configuration
    {
        private static IConfiguration _configuration;
    
        static Configuration()
        {
            var builder = new ConfigurationBuilder()
                .AddJsonFile($"appsettings.json");
    
            _configuration = builder.Build();
    
        }
        public static Browser GetBrowser()
        {
    
            if (_configuration.GetSection("BrowserConfig:Browser").Value == "Firefox")
            {
                return Browser.Firefox;
            }
            if (_configuration.GetSection("BrowserConfig:Browser").Value == "Edge")
            {
                return Browser.Edge;
            }
            if (_configuration.GetSection("BrowserConfig:Browser").Value == "IE")
            {
                return Browser.InternetExplorer;
            }
            return Browser.Chrome;
        }
    
        public static bool IsHeadless()
        {
            return _configuration.GetSection("BrowserConfig:Headless").Value == "true";
        }
    
        public static string GetEnvironment()
        {
            return _configuration.GetSection("EnvironmentSelected")["Environment"];
        }
        public static IConfigurationSection EnvironmentInfo()
        {
            var env = GetEnvironment();
            return _configuration.GetSection($@"Environments:{env}");
        }
    
    }
    
    
    public void Login()
    {
        var environment = Configuration.EnvironmentInfo();
        Email.SendKeys(environment["username"]);
        Password.SendKeys(environment["password"]);
        WaitForElementToBeClickableAndClick(_driver, SignIn);
    }
    
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
2

I'm using Visual Studio for Mac version 17.0.6.

As you can see on this screenshot it is not possible to add a reference to System.Configuration.

enter image description here

Solution:

  1. install NuGet Package - System.Configuration.ConfigurationManager.
  2. Create app.config file and set "Build action" to "EmbeddedResource"
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <appSettings>
        <add key="name" value="Joe"/>
    </appSettings>
</configuration>
  1. using System.Configuration;
  2. enjoy)

string name = ConfigurationManager.AppSettings["name"];

BTW: Do not add an app.config for a library

Dmitry Grinko
  • 13,806
  • 14
  • 62
  • 86
1

I have been trying to find a fix for this same issue for a couple of days now. I was able to resolve this by adding a key within the appsettings tag in the web.config file. This should override the .dll file when using the helper.

<configuration>
    <appSettings>
        <add key="loginUrl" value="~/RedirectValue.cshtml" />
        <add key="autoFormsAuthentication" value="false"/>
    </appSettings>
</configuration>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jason
  • 144
  • 1
  • 3
  • 11
1

Another possible solution:

var MyReader = new System.Configuration.AppSettingsReader();
string keyvalue = MyReader.GetValue("keyalue",typeof(string)).ToString();
Diligent Key Presser
  • 4,183
  • 4
  • 26
  • 34
sherite
  • 11
  • 1
1

extra : if you are working on a Class Library project you have to embed the settings.json file.

A class library shouldn't really be directly referencing anything in app.config - the class doesn't have an app.config, because it's not an application, it's a class.

  1. Go to the JSON file's properties.
  2. Change Build Action -> Embedded resource.
  3. Use the following code to read it.

var assembly = Assembly.GetExecutingAssembly();

var resourceStream = assembly.GetManifestResourceStream("Assembly.file.json");

string myString = reader.ReadToEnd();

now we have a JSON string we can Deserialize it using JsonConvert

if you didn't embed the file inside the assembly you can't use only the DLL file without the file

esamaldin elzain
  • 320
  • 1
  • 4
  • 16
0

I found the answer in this link https://stackoverflow.com/a/1836938/1492229

It's not only necessary to use the namespace System.Configuration. You have also to add the reference to the assembly System.Configuration.dll , by

  1. Right-click on the References / Dependencies
  2. Choose Add Reference
  3. Find and add System.Configuration.

This will work for sure. Also for the NameValueCollection you have to write:

using System.Collections.Specialized;
asmgx
  • 7,328
  • 15
  • 82
  • 143
-7

Here's an example: App.config

<applicationSettings>
    <MyApp.My.MySettings>
        <setting name="Printer" serializeAs="String">
            <value>1234 </value>
        </setting>
    </MyApp.My.MySettings>
</applicationSettings>

Dim strPrinterName as string = My.settings.Printer
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JMat
  • 25