The world is not beautiful

July 24, 2009

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

Filed under: Another world

from http://juststuffreally.blogspot.com/2008/02/how-to-read-appconfig-setting-for-your.html

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();
}

Comments »

The URI to TrackBack this entry is: http://adamhj.blogsome.com/2009/07/24/how-to-read-an-appconfig-setting-for-your-dll-from-your-dllconfig-file/trackback/

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>


Get free blog up and running in minutes with Blogsome
Theme designed by Jay of onefinejay.com