如何使用C#从DLL读取web.config? [关闭]

问题描述 投票:0回答:2

假设我有一个名为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属性中找到的值,我该怎么做,是否可以做到?

c# asp.net asp.net-mvc
2个回答
1
投票

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

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,告诉你config中有一个无效值。

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

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

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("");

0
投票

正如评论中已经提到的,类库项目的编译DLL没有自己的.config文件。如果您在该项目中制作了app.configweb.config,则不会将其包含在编译到DLL中的内容中。 DLL仅包含.NET代码。

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

附:这已经在SO,herehere(以及可能的其他地方)处理过。有一些关于如何实现目标的建议,但也有很多关于为什么它不是一个好主意的类似讨论。

© www.soinside.com 2019 - 2024. All rights reserved.