开发者

How to access app configuration from a .dll?

开发者 https://www.devze.com 2022-12-21 09:15 出处:网络
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.

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 so it just did Properties.Settings.Default.SomeSetting = var;Properties开发者_如何转开发.Settings.Default.Save() etc.

What are my options now that I moved that code out to a class library/.dll ?


The hosting application should handle the interface to the config file, not the DLL. Either

  1. Pass whatever settings need to be read/modified within the DLL as parameters, or

  2. 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.


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.


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


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消