我正在编写一个c#类库,需要能够从web读取设置。config或app.config文件(取决于DLL是否从ASP. config引用。NET web应用程序或Windows窗体应用程序)。

我发现

ConfigurationSettings.AppSettings.Get("MySetting")

但该代码已被微软标记为弃用。

我读到我应该使用:

ConfigurationManager.AppSettings["MySetting"]

但是,在c#类库项目中,System.Configuration.ConfigurationManager类似乎不可用。

最好的方法是什么?


当前回答

请检查您正在使用的. net版本。它应该大于4。你必须添加系统。配置系统库到您的应用程序。

其他回答

网络。配置用于web应用程序。网络。Config默认情况下有几个web应用程序所需的配置。你可以有一张网。为web应用程序下的每个文件夹配置。

app.config用于Windows应用程序。当您在Visual Studio中构建应用程序时,它将自动重命名为<appname>.exe。配置和此文件必须随应用程序一起交付。

你可以使用相同的方法从两个配置文件中调用应用程序设置值: System.Configuration.ConfigurationSettings.AppSettings(“关键”)

我强烈建议您为这个调用创建一个包装器。类似于ConfigurationReaderService,并使用依赖注入来获取这个类。通过这种方式,您将能够为测试目的隔离这些配置文件。

所以使用ConfigurationManager.AppSettings["something"];建议并返回该值。如果.config文件中没有任何可用的键,您可以使用此方法创建某种默认返回。

我一直试图找到一个解决这个问题的几天了。我可以通过在web中的appsettings标签中添加一个键来解决这个问题。配置文件。这将在使用helper时覆盖.dll文件。

<configuration>
    <appSettings>
        <add key="loginUrl" value="~/RedirectValue.cshtml" />
        <add key="autoFormsAuthentication" value="false"/>
    </appSettings>
</configuration>

我也有同样的问题。你可以这样读: System.Configuration.ConfigurationSettings.AppSettings(“MySetting”)

此外,您可以使用Formo:

配置:

<appSettings>
    <add key="RetryAttempts" value="5" />
    <add key="ApplicationBuildDate" value="11/4/1999 6:23 AM" />
</appSettings>

代码:

dynamic config = new Configuration();
var retryAttempts1 = config.RetryAttempts;                 // Returns 5 as a string
var retryAttempts2 = config.RetryAttempts(10);             // Returns 5 if found in config, else 10
var retryAttempts3 = config.RetryAttempts(userInput, 10);  // Returns 5 if it exists in config, else userInput if not null, else 10
var appBuildDate = config.ApplicationBuildDate<DateTime>();