Locating config file from .dll in both Desktop and Web applications

By | 2011.07.29

I’m using Nini for most my config needs. Nini is a .Net library for reading/writing/merging all kinds of config files. It provides a good API with type conversion, default values, etc.

To be able to access both app.config and web.config using Nini in .dll files included in test projects, desktop applications, services, web applications, webservices, etc I’ve put together a small method that automatically resolves current application configuration file by checking if it is running under web or not and resolving the correct directory+file. It also caches the response to save a few CPU cycles.

Example use with Nini

string configFile = ConfigFile;
if (!File.Exists(configFile))
    throw new Exception(string.Format("Config file \"{0}\" does not exist. Unable to continue.", configFile));
IConfigSource source = new DotNetConfigSource(configFile);

Source code for resolving config file

// References required:
// System.Configuration
// System.Web
private static string configFile = null;
/// <summary>
/// Returns config file for application
/// </summary>
public static string ConfigFile
        // Note: Untested!
        if (configFile == null)

            if (System.Web.HttpContext.Current == null)
                configFile = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None).FilePath;
                configFile = "~/Web.config".Replace("~", System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "/").Replace("/", "\\").Replace("\\\\", "\\");
        return configFile;

Leave a Reply