使用类库从 web.config/app.config 获取配置设置 [英] Getting configuration settings from web.config/app.config using class library
问题描述
3.5 中的配置设置让我发疯...救命!;)
Configuration settings in 3.5 is driving me nuts... Help! ;)
我有一个类库(命名为 ADI),它需要使用它的项目中的一些配置设置(如连接字符串、文件系统位置等).
I have a class library (Named ADI), that needs some configuration settings from the project using it (like connectionstring, filesystem locations etc).
我想在我的 Windows 窗体/Web 项目 App.Config 或 Web.Config 中定义这些设置,就像其他设置一样.
I want to define these settings in my Windows Forms/Web Projects App.Config or Web.Config, like other settings.
这是我的 windows 窗体应用程序的 app.config 的一部分:
Here is part of my app.config for my windows forms application:
<applicationSettings>
<PhotoImportRobot.My.MySettings>
<setting name="ADIImageRoot" serializeAs="String">
<value>C:DataTempADIOriginal</value>
</setting>
<setting name="ADIImageVariantsRoot" serializeAs="String">
<value>C:DataTempADIVariants</value>
</setting>
</PhotoImportRobot.My.MySettings>
</applicationSettings>
我如何从我的类库中访问它??
How do I access that from my class library??
我试过了:
System.Configuration.ConfigurationManager.AppSettings("ADIImageVariantsRoot")
怎么办?
推荐答案
如果你不追求结构化设置,appSettings 部分只需要键值对:
If you're not after structured settings, the appSettings section just takes key-value pairs:
<appSettings>
<add key="ADIImageRoot" value="C:DataTempADIOriginal" />
<add key="ADIImageVariantsRoot" value="C:DataTempADIVariants" />
</appSettings>
这将使您能够通过 AppSettings 字典访问它们:
This will enable you to access them via the AppSettings dictionary:
ConfigurationManager.AppSettings["ADIImageVariantsRoot"]
如您所料.
或者,如果您需要更多的配置结构(即不仅仅是字符串或一组设置),您可以考虑使用自己的配置部分,使用 ConfigurationSection 及其相关部分.
Alternatively, if you need more structure to your configuration (i.e. more than just strings, or a collection of settings), you can look into using a configuration section of your own, using a ConfigurationSection, and its relevant parts.
这篇关于使用类库从 web.config/app.config 获取配置设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!