Accessing the settings (app.config) of the calling

2019-07-30 16:01发布

I have a WinForms application ("WF"), and a Library called by that WinForms application ("LIB")

WF has a Settings.settings (Visual Studio Designer) and app.config combo. I gather than the designer is a front end that auto generates the app.config file. To use those settings from within WF, I use the strongly typed properties of the class it autogenerates (i.e. WF.Settings.MyTimeOutSetting).

When WF calls a method in LIB, I want to use one of WF's settings from within lib. How can I retrieve a setting from the caller's (WF's) app.config while in the callee's (LIB's) code?

4条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-07-30 16:16

The same way you would in the windows forms. It will atomically look in the app.config of the calling app first

查看更多
对你真心纯属浪费
3楼-- · 2019-07-30 16:22

The answer is: don't do it.

Have the calling application either pass you whatever you need to know in the call, or perhaps in your constructor. The called component should not require knowledge of the caller.

查看更多
Evening l夕情丶
4楼-- · 2019-07-30 16:23

Like John said, this is a bad idea. The caller (exe in this case) should pass the needed information to the DLL. That way you can re-use the DLL later, somewhere else, and not have some 'invisible' dependency on an app.config setting.

Try this:

Dim oConfiguration As System.Configuration.Configuration
oConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
Dim sValue As String = oConfiguration.AppSettings.Settings("setting").Value
查看更多
Viruses.
5楼-- · 2019-07-30 16:24

Add a reference to System.Configuration to your proejct.

Then in the particular .cs or .vb (or whatever) file you are wishing to make a reference to the config file add the following:

C#: using System.Configuration; VB: Imports System.Configuration

then you can access the web config by using something like this:

C#: System.Configuration.COnfigurationManager.AppSettings["THE_SETTING_U_WANT"] ;

VB: System.Configuration.COnfigurationManager.AppSettings("THE_SETTING_U_WANT")

IF you want a full section I think there are methods in that class to do that as well.

查看更多
登录 后发表回答