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

我发现

ConfigurationSettings.AppSettings.Get("MySetting")

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

我读到我应该使用:

ConfigurationManager.AppSettings["MySetting"]

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

最好的方法是什么?


当前回答

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

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

其他回答

另一个可能的解决方案:

var MyReader = new System.Configuration.AppSettingsReader();
string keyvalue = MyReader.GetValue("keyalue",typeof(string)).ToString();

对于如下所示的示例app.config文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="countoffiles" value="7" />
    <add key="logfilelocation" value="abc.txt" />
  </appSettings>
</configuration>

使用下面所示的代码读取上述应用程序设置:

using System.Configuration;

您可能还需要添加对System的引用。在您的项目中配置(如果还没有的话)。然后你可以像这样访问这些值:

string configvalue1 = ConfigurationManager.AppSettings["countoffiles"];
string configvalue2 = ConfigurationManager.AppSettings["logfilelocation"];

我正在用这个,对我来说效果很好:

textBox1.Text = ConfigurationManager.AppSettings["Name"];

此外,您可以使用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>();

如果你需要/想要使用ConfigurationManager类…

你可能需要通过微软的NuGet Package Manager加载System.Configuration.ConfigurationManager

工具->NuGet包管理器->管理解决方案的NuGet包…

微软文档

从医生那里有一件事值得注意…

如果应用程序需要对自己的配置进行只读访问, 我们建议你使用GetSection(String)方法。这个方法 提供对当前缓存的配置值的访问 应用程序,其性能优于Configuration 类。