13

I have a VC2010 C# Solution, with a number of projects in it.

So for example, I have a web project, and I have a class library.

In the web.config file, I have a key in the <appSettings> section, e.g.

<add key="FileDirectory" value="G:\ftproot\sales" />

I have also added a key in the Web.Production.config file to reflect the file directory on the server.

So when I reference it in my web project (It's MVC) - I do so like this:

var FTPPath = ConfigurationManager.AppSettings["FileDirectory"];

this works fine within my web project. However, I also need to reference this in the class library, which gets to my question - Is there a way to reference a key in the web.config file from another project, e.g. a class library, in the same solution??

All help is appreciated. Thanks

UpTheCreek
  • 31,444
  • 34
  • 152
  • 221
109221793
  • 16,477
  • 38
  • 108
  • 160

2 Answers2

15

Yes you can use exactly the same code. .Net will look up the configuration key in the config file of the application which started the app domain. A class library used by such an application will have access to it's config file.

Gerrie Schenck
  • 22,148
  • 20
  • 68
  • 95
  • Hi Gerrie, thanks for clearing that up. It wasn't working at the start but I added a reference for System.Configuration and it's all working fine now. I'll mark as correct once the time limit is up! – 109221793 Apr 07 '11 at 08:41
  • Thank you, I really appreciate your response. – Gerrie Schenck Apr 07 '11 at 08:49
  • how do you grab the web.config settings from a different project? This is just returning null for me. The setting I want to get is within a custom tag group section. – naz786 Feb 15 '23 at 16:26
3

class libraries do not have their own configuration. They use the configuration of which ever executable they are being used in.

This means that for you you should be able to use the same code, and it will read the setting from the config (assuming that it is there).

This is not always convenient though (for example if you write a .net based plugin for a MMC snap-in, as this means you have to modify the mmc.exe.config in the system folder.)

You might be better having a method to pass this required configuration setting into you library code. then in apps where you control the config you can just read it from there and pass it in, and in apps where you can't you can use another approach, like reading from the registry or from a manually read config file. Or have the best of both worlds and make it so you can pass it in, and if this is not done it attempts to read it from the default configuration.

This question has some more details on the pitfalls associated with dll configuration, but also has some techniques for doing it if you need to.

Community
  • 1
  • 1
Sam Holder
  • 32,535
  • 13
  • 101
  • 181