I recently broke out a part of my winform app in a .dll. Some of the classes in that dll wants fetch/store user settings. The classes just used the VS generated Settings file s
The Properties class is autogenerated. It is really a wrapper on the config file. If you don't want to change your design, just go into the code and copy it to your DLL. But remember it will no longer be magically maintained (regenerated). Or you can use ConfigurationManager to get at config file directly.
The hosting application should handle the interface to the config file, not the DLL. Either
Pass whatever settings need to be read/modified within the DLL as parameters, or
Pass in a name-value collection of settings that can be modified by the DLL, and save whatever changes are made by the DLL to the collection when control returns to the calling application.
This is similar in principle to removing a database interface from the business layer of a tiered application and encapsulating it into a data layer.
It doesn't make a lot of sense to me to have a DLL storing user settings. A DLL is a library, not an application, and doesn't directly interact with the user. If classes in the DLL need access to user settings, you can pass them in as parameters.
For those who need to read settings from userDirectory/user.config
, here is a solution:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
ConfigurationSectionGroup userSettings = config.GetSectionGroup("userSettings");
ClientSettingsSection settings = (ClientSettingsSection)userSettings.Sections.Get("[applicationName].Properties.Settings");
SettingElement elem = settings.Settings.Get([settingName]);
var sett = elem.Value.ValueXml.InnerText;
I would not recommand it (better use your own class for settings), but you can try this:
string sectionName = "applicationSettings/" +
appName + ".Properties.Settings";
System.Configuration.ClientSettingsSection section =
(System.Configuration.ClientSettingsSection)
System.Configuration.ConfigurationManager.GetSection(sectionName);
foreach (SettingElement setting in section.Settings)
{
string value = setting.Value.ValueXml.InnerText;
string name = setting.Name;
if (name.ToLower().StartsWith(searchName.ToLower()))
{
return value;
}
}