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

我发现

ConfigurationSettings.AppSettings.Get("MySetting")

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

我读到我应该使用:

ConfigurationManager.AppSettings["MySetting"]

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

最好的方法是什么?


当前回答

您需要向System添加一个引用。在项目的引用文件夹中的配置。

你绝对应该使用ConfigurationManager,而不是过时的ConfigurationSettings。

其他回答

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

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

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

微软文档

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

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

您需要向System添加一个引用。在项目的引用文件夹中的配置。

你绝对应该使用ConfigurationManager,而不是过时的ConfigurationSettings。

我在这个链接https://stackoverflow.com/a/1836938/1492229找到了答案

不仅需要使用名称空间System.Configuration。您还必须将引用添加到程序集System.Configuration.dll,通过

右键单击引用/依赖项 选择添加参考 找到并添加System.Configuration。

这肯定有用。 同样,对于NameValueCollection,你必须写:

using System.Collections.Specialized;

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

要做到这一点,您应该使用

{您的应用名称}。属性.设置。{设置名称}