如何使用C#从DLL读取web.config?

时间:2018-03-02 06:46:36

标签: c# asp.net asp.net-mvc

假设我有一个名为dummyCode.sln的项目,现在当我编译项目时,我会得到一个名为dummyCode.dll的dll。

如何使用c#读取此DLL并获取我的web.config

的信息

例如,如果我有像这样的web.config

<configuration>
 <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="employeeDB" value="Data Source=servername;Initial Catalog=employee;Persist Security Info=True;User ID=userid;Password=password;"/>
  </appSettings>
</configuration>

然后我想读取appsettings属性中找到的值,我该怎么做,是否可以这样做?

2 个答案:

答案 0 :(得分:1)

此Dll将用于某些Exe或网站。您需要将这些配置条目添加到该Exe或网站的配置文件中。

app.Config(针对Exe)和web.config(针对网站)

完成后,您可以使用以下方式阅读:

string theValue = ConfigurationManager.AppSettings["KeyName"];

(命名空间:System.Configuration

奖金,您可以创建方法来阅读不同的信息:

示例:Int

public static int GetIntConfiguration(string keyName)
{
    string value = ConfigurationManager.AppSettings[keyName] ?? "0";
    int theValue = 0;
    if (int.TryParse(value, out theValue))
    {
       return theValue;
    }
    return -1;
}

所以-1,告诉你配置中的值无效。

同样,您可以为其他类型创建方法。

编辑:根据您的评论
如果您需要打开自定义配置:

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration("dllPath.dll");

string value = config.AppSettings.Settings["key"].Value;

如果是web.config,您可以将第一行更改为:

System.Configuration.Configuration configWeb = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("");

答案 1 :(得分:0)

正如评论中已经提到的,类库项目的编译DLL没有自己的.config文件。如果您在该项目中创建了app.configweb.config,那么它不会被包含在编译到DLL中的内容中。 DLL只包含.NET代码。

这样做没有任何逻辑意义 - 设置文件应该是每个应用程序,而不是每个项目。否则它们可能相互冲突,和/或不能调整以适应包含库的应用程序。

P.S。之前已经在SO herehere(以及可能的其他地方)处理了这个问题。有一些关于你如何实现目标的建议,还有很多关于它为什么不是一个好主意的类似讨论。