December 06, 2006

dotNET - Use app.config ApplicationSettings and UserSettings

When using Settings in an Assembly or .exe you can use the Settings Designer to generate a config file using Settings. The Settings Designer provides a wrapper class which allows you to provide defaults and access the config data using Properties.
But what if you're not working inside that Assembly or .exe? this presents a problem.
If your loading the Assembly externally and want to access that Assembly's .config file you'll probably wish to use something in the System.Configuration namespace... unfortunately it's not of much use if you've created the .config file from the Settings Designer in Visual Studio!!
This is because the Designer creates Sections and ApplicationSettings and UserSettings, the System.Configuration namespace does not provide a method to access these (it has a method to access AppSettings which are a different thing.
Below I've written a workaround which locates the app.config and accesses the ApplicationSettings and UserSettings using XML instead of System.Configuration.

_server = GetAssemblySettingOrDefault(Path.Combine("C:\temp\MyAssembly.dll"), "serverLocation", "http://localhost/mydefaultserver/mydefaultserver.asmx");



Return a key/value list of ApplicationSettings and UserSettings for a given .exe's of .dll's .config file.


public static KeyValueConfigurationCollection GetAssemblySettings(string assemblyPath)

{
Configuration config = ConfigurationManager.OpenExeConfiguration(assemblyPath);

XmlDocument dom = new XmlDocument();
dom.Load(config.FilePath);

//UserSettings and ApplicationSettings
KeyValueConfigurationCollection returnList = new KeyValueConfigurationCollection();

string[] settingsTypes = { "applicationSettings", "userSettings" };
foreach (string settingType in settingsTypes)
{
XmlNode node = dom.SelectSingleNode("//configuration//" + settingType);
if (node != null)
{
try
{
if (node.HasChildNodes)
{
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode.HasChildNodes)
{
foreach (XmlNode settingNode in childNode.ChildNodes)
{
if (settingNode != null)//the Settings node
{
if (settingNode.Attributes.Count > 0) //there should be at least one attribute
returnList.Add(settingNode.Attributes[0].Value, settingNode.InnerText);//the setting name and the setting/value
}
}
}
}
}

}
catch { throw; }
}
}
return returnList;
}

// Get the value of the Assembly ApplicationSetting or UserSetting from the key.
// If the key does not have a value then return the default supplied by the caller.

public static string GetAssemblySettingOrDefault(string assemblyPath, string assemblySettingKey, string assemblySettingDefaultValue)
{
string result = assemblySettingDefaultValue;
KeyValueConfigurationCollection settings = GetAssemblySettings(assemblyPath);
if(settings != null)
{
KeyValueConfigurationElement key = settings[assemblySettingKey];
if(key != null)
result = key.Value;
}
return result;
}

14 comments:

Anonymous said...

Thanks...works for me.

Sameer said...

You are a Champ. Thanks

ASP NET Web Services said...

Great work dude.... keep it up...

DotNetURL said...

Hi,

Nice blog..publish you new content url at http://www.dotneturl.com and get reader and back link form us for free

web design company,web designer,web design India,website design,web design said...

Thanks u r information

bollywood girls said...

i like your blog ....

Suparna said...

Thank you for sharing such an informative article with us.
Web Design  |   Web Designer

梦中林 said...

When the Wow Gold wolf finally found the Buy Wow Goldhole in the chimney he crawled wow gold cheap down and KERSPLASH right into that kettle of water and that was cheapest wow gold the end of his troubles with the big bad wolf.
The next day the cheap wow gold little pig invited his mother over . She said "You see it is just as mygamegoldI told you. The way to get along in the world is to do world of warcraft gold things as well as you can." Fortunately for that little pig, he buy cheap wow gold learned that lesson. And he just k4gold lived happily ever after!

Anonymous said...

come to visit my .NET space : http://enterdotnet.blogspot.com

Anonymous said...

dessicant air dryerpediatric asthmaasthma specialistasthma children specialistcarpet cleaning dallas txcarpet cleaners dallascarpet cleaning dallas

vero beach vacationvero beach vacationsbeach vacation homes veroms beach vacationsms beach vacationms beach condosmaui beach vacationmaui beach vacationsmaui beach clubbeach vacationsyour beach vacationscheap beach vacations

bob hairstylebob haircutsbob layeredpob hairstylebobbedclassic bobCare for Curly HairTips for Curly Haircurly hair12r 22.5 best pricetires truck bustires 12r 22.5

washington new housenew house houstonnew house san antonionew house ventura

Anonymous said...

new houston house houston house txstains removal dyestains removal clothesstains removalteeth whiteningteeth whiteningbright teeth

jennifer grey nosejennifer nose jobscalebrities nose jobsWomen with Big NosesWomen hairstylesBig Nose Women, hairstyles

Anonymous said...

black mold exposureblack mold symptoms of exposurewrought iron garden gatesiron garden gates find them herefine thin hair hairstylessearch hair styles for fine thin hairnight vision binocularsbuy night vision binocularslipitor reactionslipitor allergic reactionsluxury beach resort in the philippines

afordable beach resorts in the philippineshomeopathy for eczema.baby eczema.save big with great mineral makeup bargainsmineral makeup wholesalersprodam iphone Apple prodam iphone prahacect iphone manualmanual for P 168 iphonefero 52 binocularsnight vision Fero 52 binocularsThe best night vision binoculars here

night vision binoculars bargainsfree photo albums computer programsfree software to make photo albumsfree tax formsprintable tax forms for free craftmatic air bedcraftmatic air bed adjustable info hereboyd air bedboyd night air bed lowest price

Anonymous said...

find air beds in wisconsinbest air beds in wisconsincloud air beds

best cloud inflatable air bedssealy air beds portableportables air bedsrv luggage racksaluminum made rv luggage racksair bed raisedbest form raised air bedsbed air informercialsbest informercials bed airmattress sized air beds

bestair bed mattress antique doorknobsantique doorknob identification tipsdvd player troubleshootingtroubleshooting with the dvd playerflat panel television lcd vs plasmaflat panel lcd television versus plasma pic the bestadjustable bed air foam The best bed air foam

hoof prints antique equestrian printsantique hoof prints equestrian printsBuy air bedadjustablebuy the best adjustable air bedsair beds canadian storesCanadian stores for air beds

migraine causemigraine treatments floridaflorida headache clinicdrying dessicantair drying dessicant

rduht said...

we offer wow power leveling and wow gold wow gold