App.Config for your DLL

AI权益加码!Claude Code、Cursor等20+工具免费用! 购周边限时加赠Coding Plan Lite,畅享主流AI工具!学习进阶更高效! 阅读详情

http://www.codeproject.com/dotnet/DLLAPPCONFIG.asp

By n10sive

Introduction

When developing DLLs for distribution, it is often desired to have an app.config file associated with that DLL. However, the .NET 1.1 Framework only allows a single app.config and it is usually associated with the running application. This really leaves developers in a pinch as they do not know if an application is using an app.config to "merge" its entries into, or they require the application developer to include entries into their config file for DLL usage.

Background

One method commonly used is to write your own XML file and put your configuration info there. This method has several drawbacks. What if you have included a third party DLL that has configuration information that it expects to see in an app.config file? You are now stuck with the same problem. One such case of this problem arises when you use the Microsoft Enterprise Library in your DLL. The Libraries configuration tool adds a line into the app.config file that points to its own config file for internal use. When you call a library class, it looks in the app.config file for the name of its own config file. Things get ugly from here.

If you have attempted to Google an answer to this problem, you will find "can't be done". This article will explain how it can be done.

I want to start by stating the following disclaimer(s): It is not a normal practice to use reflection to "patch" back another class. This example is an extreme case to get around what I consider is a serious flaw in the .NET Framework. Portability was not a factor when developing this technique. This technique is not needed with .NET 2.0 in my understanding. All that said, let's get started.

Using the code

The .NET Framework reads the application configuration file into a static hashtable whenever the application domain is first referenced. Once it is read, it cannot be reread or modified. This is unfortunate as it does not allow us to call any methods or properties to alter this behavior. Not accepting that there is no workaround, I started to snoop into the .NET Framework System.Dll file using Lutz Roeder's .NET Reflector. What I found is that you can make the framework reread the config file if you reset its internal variables into thinking that the app.config file has not been read. Doing this is ugly, but desperate people take desperate measures.

The following code is a simple class to demonstrate how to do this. I will leave it up to the reader to put this in your own code.

The main point of all this is to change the ConfigurationSettings class static variable "_configurationInitialized" to false, and null out the "_configSystem". Doing so will make the framework read the app.config file into memory. It is very important to undo the changes made before you leave. If not, the using application will now be pointing at your DLL's config file. One method to ensure this safety is to wrap your config parameters into a class. I have added a static ConnectionString method to this class for demonstration purposes. It uses the C# "using" statement to make sure that our object is destroyed, and that "Dispose" is called to undo our changes. You can wrap calls to the Enterprise Library, or another third party DLL the same way.

internal class MyDllConfig : IDisposable
{
    private string _oldConfig;
    private bool _libCompat;
    private const string _newConfig = "mydll.dll.config";
    // don't forget to rename this!!

    internal MyDllConfig()
    {
        _libCompat = Assembly.GetAssembly(typeof(
          ConfigurationSettings)).GetName().Version.ToString().
          CompareTo("1.0.5000.0") == 0;
        _oldConfig = AppDomain.CurrentDomain.GetData(
               "APP_CONFIG_FILE").ToString();
        Switch(_newConfig);
    }
    protected void Switch(string config)
    {    
        if ( _libCompat )
        {
            AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE",config);
            FieldInfo fiInit = typeof(
                System.Configuration.ConfigurationSettings).GetField(
                    "_configurationInitialized",
                    BindingFlags.NonPublic|BindingFlags.Static);
            FieldInfo fiSystem = typeof(
                System.Configuration.ConfigurationSettings).GetField(
                    "_configSystem",BindingFlags.NonPublic|BindingFlags.Static);
            if ( fiInit != null && fiSystem != null )
            {
                fiInit.SetValue(null,false);
                fiSystem.SetValue(null,null);
            }
        }
    }

    public void Dispose()
    {
        Switch(_oldConfig);
    }

    public static string ConnectionString()
    {
        string cstr;
        using ( new MyDllConfig() )
        {
            cstr = ConfigurationSettings.AppSettings["ConnectionString"];
        }
        return cstr;
    }
}

Points of Interest

I have place a small sanity check into this class that checks the version number of the System DLL that this was written for. If another version is detected, this patch is bypassed.

The AppDomain has a property SetupInformation that has a ConfigurationFile property. I found that if you set your app's config file name using this property then it is ignored. Using the SetData method causes the class to re-initialize this variable and gives us our desired results, including adding the application path onto our filename for us!

The Visual Studio IDE will allow you to place a generic app.config file into your DLL project. Adding the following line to your post build events will copy and rename this file to the appropriate place.

Copy $(ProjectDir)app.config $(TargetPath).config

About n10sive


Been involved in computer hardware and software since 1977. Experience includes Windows, Unix and embedded realtime systems. I own a software development company ("It's good to be the King!")and have been CTO and Lead Engineer for both small and large companies.

comment:

internal MyDllConfig(string configFileName)

DLL执行中获取App.config中的值 今天在一个自己的Windows Service项目里通过反射执行DLL中的方法,该方法在执行时使用DLL项目的配置参数(保存在app.config里)。在CodeProject上有个很老的办法(原文地址 http://www.codeproject.com/KB/dotnet/dllappconfig.aspx?msg=2823743 ):Imports System.IOImport 阅读详情

相关推荐

.net类库获取当前类库的配置(dllapp.config读写)

dllapp.config如下:               web中的config如下:              ================================ 读取方法如下: public string GetDLLAppKey()        {            string filePath = System.Reflectio

cxzhq2002的杂记 2134

.net项目中,因为App.config的原因,导致引用同一个dll的不同版本报错

项目中引用的两个类库中都用到了Newtonsoft.Json的类库,开发调试的时候没有出现问题,可在单独部署后总是会报版本不匹配的错误,一点点找原因,最后发现原来项目的配置文件App.config中,我删除了以下这段节点内容,从而导致报错 <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <ass

圈儿圈儿 514

C#根据 App.config 文件中的配置信息去查找并加载指定目录下的 DLL

C#根据 App.config 文件中的配置信息去查找并加载指定目录下的 DLL

zgscwxd的博客 1222

C# 类库 读取 app.dll.config 配置文件的问题

app.config文件仅供exe工程读取的,想多数操作一样,使用 ConfigurationManager.AppSettings["key"]   就可以正常读取。在调试dll工程时,需要单独指定config文件才能正确读取key值。 static string configPath = System.Reflection.Assembly.GetExecutingAssembly().Loc...

fanfan513的专栏 6320

.NET中从app.config或web.config读取设置

我正在使用一个C#类库,该类需要能够从web.configapp.config文件中读取设置(取决于DLL是从ASP.NET Web应用程序还是Windows Forms应用程序引用的)。

asdfgh0077的博客 1771

winform的app.config

在开发Web项目的时候,会有一个配置文件Web.config,用来存放一些全局的变量,如连接数据库用的字符串。相应的,在开发winform程序时,也有一个配置文件,它就是App.config,这个文件的作用与Web.config大致相同,也可以用来存放程序所用的全局变量及Valu

霜叶红于二月花 5434

WPF:exe.configapp.config文件

在WPF工程里面会有两个config,一个是.exe.config,另一个是app.config。 如果需要用到config去保存设置,需要在app.config里面添加settings,如下修改: <?xml version="1.0"?> 读取的时候,在代码中使用如下方法: string debug = System.C...

ayouayouwei 2727

VS2012 C# dll工程默认的app.config文件

项目工程里有一些dll工程是继承自UserControl的,打开Designer画面时,发生错误。查了半天是读取app.config文件失败。加了app.config文件也丝毫无用。利用代码   AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;   将VS2012 IDE默认读取的config打出后是这个   C:\Use

hunter2236的专栏 2220

log4net配置与app.config文件

给自己的项目加入日志功能,

熊孩子会撒野 5778

多个WINFORM项目(多个EXE)共用一个APP.CONFIG

  点击每个项目的右键属性——生成——输出——输出路径,这个路径最好是在主项目下建一个活页夹(比如file),输出路径就选择这个路径。  点击主项目的右键属性——发布——发布位置可选择自己指定的一个地方。安装模式和和设置选择第二项,点击“应用程序文件”按钮,列出应用程序列表,系统必备的就不管了,但是如果是编程人员手动加入引用的DLL文件、exe文件、exe.confige文件等必须把发布状态改

君之水 5862

类项目中的配置文件app.config在打包安装后的信息获取的问题

<br />在一个项目中碰到这样的一个问题,做一个WORD插件,功能在类库项目中实现了,配置信息存在类库项目的配置文件app.config中,在进行打包后,获取的配置文件中的DocType节点信息时,使用以下方法  ConfigurationManager.AppSettings["DocType"]获取的值总是获取不到,跟踪调试发现值为null,上网看到类库被应用以后,ConfigurationManager.AppSettings访问的是应用程序的配置文件而不是类库所用的配置文件了,所以只有改变策略,把

jackmacro的专栏 4655

C# 通过ConfigurationManager读写配置文件App.Config

App.config 是 C#中最常用的配置文件类型。 通常位于项目的根目录中,以 XML 格式存储配置信息。App.config 文件可以包含多个配置节,如 appSettings、connectionStrings、system.web 等,用于存储不同的配置信息。如图资源管理器中引用中可以看到它的身影。它是引用.net库中的System.Configuration.dll文件。

C/C#、Android driver、STM32、Linux等等。 1579

Config windows Service Name in App.config

In your integration service project, 1.       Edit ProjectInstaller.Designer.cs, check if the Service Installer has been well configured // // serviceInstaller // this.serviceInstaller.ServiceN

alien1的博客 558

C# 将引用的DLL放入指定文件夹

C# 将引用的DLL放入指定文件夹 一、找到程序中的App.config文件,没有就创建一个config文件;然后添加下面的代码: <?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup&g

韬光养晦 5727

App.Config详解及读写操作

App.Config详解 应用程序配置文件是标准的 XML 文件,XML 标记和属性是区分大小写的。它是可以按需要更改的,开发人员可以使用配置文件来更改设置,而不必重编译应用程序。配置文件的根节点是configuration。我们经常访问的是appSettings,它是由.Net预定义配置节。我们经常使用的配置文件的架构是象下面的形式。先大概有个印象,通过后面的实例会有一个比较清楚的认识...

weixin_33937499的博客 356

有关winform 配置文件 app.config

   1、和Asp.net的Web.config不同,创建winform应用时并不会默认的创建app.config。     2、如果你选定项目-添加新项-应用程序配置文件,不更改默认的App.config名称,那么你得到一个符合要求的最小的App.config文件。注意,若你生成该项目,bin目录下面会出现一个复制了App.config内容的名字为应用程序名.exe.config的配置文件。  

qianhe_he的专栏 1847

引用的dll路径问题

引用的dll路径问题 1、问题背景 在.Net项目中我们经常会引用一些dll,但是这些dll会默认在可执行文件目录下。如果dll较多,会显得该目录很臃肿。如果我们可以另外建一个目录专门存放这些dll就比较好。 2、解决方案 https://blog.csdn.net/xiaominggunchuqu/article/details/78749391 可参考上述博客地址,在app.config配置文件中进行配置。 <configuration> <runtime> <

目标:MVP 1229
上一篇: An application to fetch the release sources from Visual SouceSafe based on an Excel migration plan
下一篇: REGEDIT.exe
cnlike
博客等级 码龄22年 1粉丝 26原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值