Wednesday, February 13, 2008

How to read an app.config setting for your DLL from your dll.config file

It turns out you can manually read the app.config settings for your DLL, using the ConfigurationManager.OpenMappedExeConfiguration. This is pretty darned ugly, but it works. It will look in the location of the currently executing assembly (ie. you dll's location) for the file "{dllname}.config". You still need to manually deploy the config file to this location - the setup package only deploys the EXE config file.

To get the code working, first add a reference to the .Net "ConfigurationManager" to your project, then add "using System.ConfigurationManager" to your class.

public string getOpenedConfigValue(string keyName)
{
string codebase =
System.Reflection.Assembly.GetExecutingAssembly().
CodeBase;
Uri p = new Uri(codebase);
string localPath = p.LocalPath;
string executingFilename =
System.IO.Path.
GetFileNameWithoutExtension(localPath);

string sectionGroupName = "applicationSettings";
string sectionName =
executingFilename + ".Properties.Settings";

string configName = localPath + ".config";
ExeConfigurationFileMap fileMap =
new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = configName;
Configuration config =
ConfigurationManager.OpenMappedExeConfiguration(
fileMap,ConfigurationUserLevel.None);
ConfigurationSectionGroup group =
config.GetSectionGroup(sectionGroupName);
ClientSettingsSection section =
(ClientSettingsSection)group.Sections[sectionName];
SettingElement elem = section.Settings.Get(keyName);

if (elem == null)
return "";
else
return elem.Value.ValueXml.InnerText.Trim();
}

No comments: