简体   繁体   English

从链接的dll读取app.exe.config文件的设置的简单方法

[英]simple way to read settings of an app.exe.config file from a linked dll

Is there a simple way to read from the global application.exe.config file from a dll? 有没有一种简单的方法可以从dll中读取全局application.exe.config文件? Currently I am loading the file as an XmlDocument but I wonder if there is a better solution. 目前,我正在将文件加载为XmlDocument,但我想知道是否有更好的解决方案。

That's what I mean: 那就是我的意思:

  • If I create a new WinForms Project I have a Settings Tab in the Project properties where I can add some simple values (And I want to access the per Application settings, not the user beased ones). 如果我创建一个新的WinForms项目,则在项目属性中有一个“设置”选项卡,可以在其中添加一些简单的值(并且我想访问每个应用程序的设置,而不是用户使用的设置)。
  • From my code I can access these values with: 从我的代码中,我可以使用以下方式访问这些值:

     Console.WriteLine(Properties.Settings.Default.SomeValue); 

The Settings class is autogenerated in the file Settings.Designer.cs. Settings类在文件Settings.Designer.cs中自动生成。

Now I have the case where a dll need's to read the settings from the Main Application's config file. 现在,我有一个dll需要从主应用程序的配置文件中读取设置的情况。 Is there a simple way to achive this? 有没有简单的方法可以做到这一点? Currently I am reading the file as an XML Document. 目前,我正在将文件读取为XML文档。

If you implement an ApplicationSettingsBase in your DLL, it will actually read the application.exe.config anyway - you just need to add the relevant config sections to it. 如果您在DLL中实现ApplicationSettingsBase ,则无论如何它实际上都会读取application.exe.config-您只需要向其中添加相关的config部分。 The .dll.config file output by the compiler is generally a useless piece of crap, because the DLL won't even look at it. 编译器输出的.dll.config文件通常是无用的废话,因为DLL甚至不会看它。

The easiest way to get what you want is to add yourself a settings file to the DLL and use it within the DLL - when the app.config is generated, copy those sections over to the app.config file in the executable. 获得所需内容的最简单方法是将自己设置文件添加到DLL并在DLL中使用它-生成app.config时,将这些部分复制到可执行文件中的app.config文件中。 (Unfortunately this isn't automated, it should be). (不幸的是,这不是自动的,应该是)。

It depends on where the properties belong. 这取决于属性所属的位置。

If you create a Settings file in your dll you can just copy the config section to app.config of the main file and your dll will read its settings as usual. 如果您在dll中创建一个设置文件,则只需将config部分复制到主文件的app.config中,您的dll将照常读取其设置。

If the settings are "global", you can change the "Access modifier" in the settings designer from Internal to Public. 如果设置是“全局”,则可以在设置设计器中将“访问修饰符”从“内部”更改为“公共”。 But you need to reference the main project, but that usually creates circular references. 但是您需要引用主项目,但这通常会创建循环引用。 The way to solve that is to create a class library with the global settings (change modifier to public) that you can reference from all of your projects. 解决该问题的方法是使用可以从所有项目中引用的全局设置(将修饰符更改为public)创建一个类库。

var fooSettingValue = SettingsProject.Properties.Settings.Default.FooSetting;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM