Reading other app.config files

Since VS 2005 its been really easy to read / write app.config properties thanks the to the strong typed Properties.Settings class created for us by Visual Studio. However reading / writing properties of a app.config which belongs to other application isn’t as straight forward. Why would you want to do this anyway? well, perhaps the app.config belongs to a Windows service and you want to give users the ability to alter settings from a configuration application written using windows forms.

The following code requires you to add System.Configuration to your references.

public static void UpdateAppConfigValue(string SettingName, string NewValue)
{
string sConfigFileName = “OwnerApp.exe.config”;
string sSettingsSection = “OwnerApp.Properties.Settings”;
string sSettingName = SettingName;
string sValue = NewValue;

ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = sConfigFileName;

Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

ConfigurationSectionGroup grpApp = config.GetSectionGroup(“applicationSettings”);
ClientSettingsSection secPropSet = (ClientSettingsSection)grpApp.Sections[sSettingsSection];

secPropSet.SectionInformation.ForceSave = true;

SettingElement elm = secPropSet.Settings.Get(SettingName);
elm.Value.ValueXml.InnerText = NewValue.Trim();

config.Save();
}

public static string GetAppConfigValue(string SettingName)
{
string sConfigFileName = “OwnerApp.exe.config”;
string sSettingsSection = “OwnerApp.Properties.Settings”;
string sSettingName = SettingName;

ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = sConfigFileName;

Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

ConfigurationSectionGroup grpApp = config.GetSectionGroup(“applicationSettings”);
ClientSettingsSection secPropSet = (ClientSettingsSection)grpApp.Sections[sSettingsSection];

secPropSet.SectionInformation.ForceSave = true;

SettingElement elm = secPropSet.Settings.Get(SettingName);

return elm.Value.ValueXml.InnerText.Trim();
}

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: