use*_*673 6 dll configuration-files .net-3.5
我需要一个.NET 3.5 DLL有自己的配置文件.可以从许多不同的应用程序调用此DLL,因此存储在配置文件中的信息(如连接字符串)需要保存在DLL可以引用的配置文件中.我想要的是当使用DLL时,我需要"切换"用于引用信息的配置文件作为DLL配置文件.然后,当使用配置信息完成DLL时,交换机将恢复为默认值.DLL是使用.NET 3.5编写的.我一直在寻找如何做到这一点,我一直在寻找的是如何将信息与exe的app.config文件合并.在我的情况下,我不知道这个DLL将如何用于修改任何exe的app.config文件.这个解决方案需要独立存在.但是,我用于创建DLL(包含业务对象)的基类期望在配置文件中查找连接字符串和其他信息,这就是为什么我需要在其时"切换"到我的DLL配置文件的原因.访问,然后切换回来,所以我不搞乱调用DLL的exe应用程序.
.NET 2.0及更高版本的配置系统为您提供了功能 - 您可以根据需要加载特定的配置文件.这是一项更多的工作 - 但它的工作原理.
你必须做这样的事情:
// set up a exe configuration map - specify the file name of the DLL's config file
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = "ConfigLibrary.config";
// now grab the configuration from the ConfigManager
Configuration cfg = ConfigurationManager
.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
// now grab the section you're interested in from the opened config -
// as a sample, I'm grabbing the <appSettings> section
AppSettingsSection section = (cfg.GetSection("appSettings") as AppSettingsSection);
// check for null to be safe, and then get settings from the section
if(section != null)
{
string value = section.Settings["Test"].Value;
}
Run Code Online (Sandbox Code Playgroud)
您还需要确保正在构建类库DLL的配置并将其复制到可以获取它的位置.最糟糕的情况是,您需要指定特定的配置文件,并通过在Visual Studio属性窗口中设置其"复制到输出目录"属性来确保将其复制到输出目录.
您还应该查看Jon Rista关于CodeProject上.NET 2.0配置的三部分系列.
强烈推荐,写得很好,非常有帮助!
渣
| 归档时间: |
|
| 查看次数: |
4676 次 |
| 最近记录: |