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
1 2 3 4 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// References required: // System.Configuration // System.Web private static string configFile = null; /// <summary> /// Returns config file for application /// </summary> public static string ConfigFile { get { // Note: Untested! if (configFile == null) { if (System.Web.HttpContext.Current == null) configFile = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None).FilePath; else configFile = "~/Web.config".Replace("~", System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "/").Replace("/", "\\").Replace("\\\\", "\\"); } return configFile; } } |