58

I did not realize that: 'have a web.config in a separate class library and' was reading the web.config app setting from different web application.

I am using VS2010 target framework 3.5

I don't know what is wrong here but I am getting null when I try to get ConfigurationManager.AppSettings["StoreId"];

private string _storeid = GetStoreId;

public static string GetStoreId
{
    get
    {
        return ConfigurationManager.AppSettings["StoreId"];
    }
}

web.config:

<appSettings>
    <add key="StoreId" value="123" />
</appSettings>
2
  • Is this in your main app? In a class library? In a web application or web site??
    – marc_s
    Nov 25, 2010 at 21:36
  • Hi @Nick can you please revise the correct answer? It's been 7 yrs and I posted a better solution. Aug 7, 2018 at 11:39

13 Answers 13

66

If you are UNIT TESTING you need A COPY of the APP.CONFIG inside the UNIT TEST PROJECT

5
  • 5
    At the very least make a shortcut file to the App.Config - in general you should never duplicate code files unless via a version control system. If you can try do it with DI and Mocking the App.Config in your unit tests. Nov 27, 2016 at 22:50
  • 3
    This was the solution to my issue. I had to pull the tags from my web.config and put them in the app.config in between the <configuration> branch. Once I did that my unit testing started working beautifully. Sep 6, 2017 at 14:48
  • 1
    Why do we have to scroll down so far to get this answer? Can someone move it up? Apr 25, 2018 at 10:43
  • 2
    I think i must have trained myself to ignore any posts with caps lock in them, because I scrolled straight past this at first... and then scrolled back up and realised this was the exact solution to by problem...
    – F1Krazy
    Aug 28, 2019 at 15:41
  • I agree with what @JeremyThompson wrote. However, instead of "shortcut", I would call it link. Meaning create a link to your file inside another project. I would recommend to simply put the configuration file in a shared folder under the solution and have the relevant projects all share it by adding a linked file inside each project. This is what was mentioned in this solution here (stackoverflow.com/a/60107554/4441211) and I think it is complementary to this solution. Oct 25, 2021 at 6:56
23

Update

You can have an AfterTargets in your CsProj file that copies the config:

<Target Name="CopyAppConfig" AfterTargets="Build" DependsOnTargets="Build">
    <CreateItem Include="$(OutputPath)$(AssemblyName).dll.config">
         <Output TaskParameter="Include" ItemName="FilesToCopy"/>
    </CreateItem>
    <Copy SourceFiles="@(FilesToCopy)" DestinationFiles="$(OutputPath)testhost.dll.config" />
</Target>

Problem

The usual cause for this is due to context.

Cause

When you have a solution with two projects, if the App/Web.Config is in the main project it wont work if the context of the running application is the second project such as a library, unit test, etc.

Conundrum

To read values from the config in other projects (with System.Configuration) you'll need to move/copy the config file to the project with the running context. Unfortunately duplicating files defeats the tenants of good programming; OOP, Source Code Management, SOLID, etc.

Cool Solution

A nifty solution is adding config file shortcuts in other projects so you only update one file:

enter image description here

It would be nice to divide the contents of config files across project's. Elegantly, like Sharing Assembly Files as per answer #2: https://stackoverflow.com/a/15319582/495455 but alas it's by context

5
  • 3
    Same goes for a console app referencing and calling into a class library. Settings go into console's app.config and can be called from class library like ConfigurationManager.AppSettings["myKey"]
    – aponzani
    Jan 16, 2013 at 17:03
  • 1
    Downvoted. This is fighting symptoms, not fixing problems. This makes future updates error prone, as you may want to have separate config values for each project.
    – Spikee
    Mar 5, 2019 at 8:01
  • @Spukee can you provide àn answer with à solution? Mar 5, 2019 at 12:17
  • @JeremyThompson: The accepted answer is fine. My main concern is that providing a link will give you a false sense of security. Maintaining each file separately requires a little more discipline but that's never a bad thing. It also means you are very aware of what's going on, rather than 'assume' everything is okay.
    – Spikee
    Mar 5, 2019 at 14:02
  • 2
    The accepted answer is fine - no it isn't even a solution. You can see the file in Solution Explorer is a shortcut, sorry I'm not catering for people who want to maintain copies of essentially the same file! Rookies. Mar 5, 2019 at 21:41
12

Disclaimer ;) This post is not to answer OP as it is too late but definitely it would help the readers who end up to this page.

Problem I faced : ConfigurationManager.AppSettings["uName"] returning null in my C# web api project.

Basic Things I checked for :

1) In code ConfigurationManager.AppSettings["uName"] , I was using exact key 'uName' as I had in web.config file,

i.e

<appSettings>
      <add key="uName" value="myValue" />
</appSettings>

Checked that I haven't mis typed as userName instead of uName etc.

2) Since it is a Web API project it would have a file as web.config instead of app.config , and that too in root folder of your project. [refer the image].

enter image description here

Solution :

The solution that worked for me ,

Changed ConfigurationManager.AppSettings["uName"] to WebConfigurationManager.AppSettings["uName"]

and

made sure that I had

<appSettings>
          <add key="uName" value="myValue" />
</appSettings>

in the right file ie.

Right file is not web.config in View folder

neither the debug or release web.config

enter image description here

2
  • This was my mistake. I was using the wrong web config. AppSettings is in the other web config. Thank you for your help :) May 1, 2018 at 19:35
  • @BernardV, happy to help :) !!
    – eRaisedToX
    May 1, 2021 at 10:08
8

and:

<appSettings>
    <add key="StoreId" value="123" />
</appSettings>

is located in the web.config file of your ASP.NET application and not in some app.config file you've added to your class library project in Visual Studio, right? You can't be possibly getting null if this is the case. If you've added this to an app.config of you class library project in Visual Studio then getting null is perfectly normal behavior.

2
  • its located in web.config in my web application
    – Nick Kahn
    Nov 25, 2010 at 22:15
  • 7
    its worth noting that if you have a test harness running the code, then its app.config needs to have the setting you are looking for.
    – KevinDeus
    Feb 21, 2013 at 1:42
2

I just got answer DLL are called from another project not in the project where there are create.so entries in App.config should b move to calling project config file.

For example i have 2 project in my solution one class library and other console application.i have added class library reference in Console application.So if i add app.config file in class library project it through null exception.it works when i added app.config in console application.Hope it works

2

App settings are loaded into ConfigurationManager.AppSettings, but User settings (in Properties settings in your project properties) are not.

2

In Visual Studio, right-click on the config file, select Properties, and then change "Copy to Output Directory" to either "Copy always" or "Copy if newer".

Alternatively, manually add the following section as a child of the element in your .csproj file (this one is for "Copy always" for file "App.config"):

  <ItemGroup>
    <None Update="App.config">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>
1

I tried all of these solutions but none worked for me. I was attempting to use a 'web.config' file. Everything was named correctly and the files were in the proper location, but it refused to work. I then decided to rename my 'web.config' file to 'app.config' and just like that, it worked.

So if you are having this issue with a 'web.config' file be sure to rename it to 'app.config'.

0

This happened to me when I was testing a Class Library (.dll). They were both in the same project but the App.config for the library had the settings I needed. The App I had written to test needed the settings because it was running the library.

0

I got this problem as I copied a project from the file explorer and renamed the project. This copied the Debug folder and as I didn't have it set to 'Copy if newer' it didn't overwrite the old App.config file.

Just delete the Debug folder and rebuild. Hope that helps someone.

0

I agree with above answer and I would like to add few more points

  1. you should make sure you don't put space before and after the : see code below:

    private static string Client_ID = ConfigurationManager.AppSettings["ida:ClientId"];
    

    if you put space between ida: ClientId it will not work and will return null

  2. make sure your key value names are correct

  3. you can try WebConfigurationManager

0

Happened to me just now, only when calling it from another project. Apparently, at the other project, the reference has not been defined as a Service Reference but rather as a Connected Service. I deleted the reference and added it again.

0
string setting = ConfigurationManager.AppSettings["Setting"];
  1. Make sure config file is in the same folder as code referencing it. Create a helper class if it is not. Duplicating this could cause confusion should someone forget it exists in two places.
  2. Keep app settings in an app.config and not a web.config for AppSettings.I had this issue with a key in the web.config.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.