.netconfigurationconfiguration-filesclass-library

How can I make a .NET class library read its own configuration file?


I have a .NET class library that provides a set of helper functions that are used by several Web Services. This class library must store a single setting, specifically, a connection string, which need not be seen by the Web Services themselves, since they all must query the same datbase.

Unfortunately, .NET provides no means to easily read a DLL's app.config file. The only "easy" solution would be to store the connection string in every single Web Service configuration file, which is completely bollocks.

Normally, I care about code elegance, but this time I really need a solution, even if it is a hack. Is there any way to make a .NET class library have its own configuration?


EDIT: Technically, I could merge all those Web Services into a single Web Service. But, for business reasons (each Web Service will be sold separately), I cannot do that.


Solution

  • I think you're looking for:

    ConfigurationManager.OpenExeConfiguration(string exePath)
    

    or

    ConfigurationManager.OpenMappedExeConfiguration(
        new ExeConfigurationFileMap() { 
            ExeConfigFilename = path + "app.config" 
        }, ConfigurationUserLevel.None);
    

    Which returns a Configuration object. MSDN doc on ConfigurationManager

    Try this question for how to get the DLL path.