How to use application config of imported C # project

I am using Visual Studio 2010 and C # 4.0. I have a project that provides an interface for a web service. It has an app.config that defines the bindings for the web service. I want to show this project as a library for other clients to use.

However, when I try to import this library project into a client project (say a console application), I get an error because it could not find the configuration file associated with the web service.

Is there a way to use app.config in my library project so that my clients can use it without having to define their own config file?


source to share

2 answers

How about a little change to the library project:

  • Change app.config in the build action of the library project to Embedded Resource.
  • Change the code while reading config, check if config exists, if not pull app.config from Embedded Resource to current folder and then use something like ConfigurationManager. OpenMappedExeConfiguration to read it.

After that, any project uses this library so as not to worry about these settings.



First, create a utility function as shown below. This function should be in a library or class that can be called from your web service (and of course your main project). Better to add a link to this library in your webservice.

    public static string GetAppConfigValue(string key)
        return ConfigurationManager.AppSettings[key] ?? GetAppConfigValue(GetAppConfigFileName(), key);

    private static string GetAppConfigValue(string appConfigFileName, string key)
        ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
        fileMap.ExeConfigFilename = appConfigFileName;
        Configuration appConfig = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
        return appConfig.AppSettings.Settings[key].Value;


Now, if you can call GetAppConfigValue(string)

from your main project, it will return the value of the cached app.config as this is its own config file. You can also call the public function from the web service project when it returns the configured configuration parameters. The tricky part here is specifying the full path to the config file correctly!



All Articles