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

我发现

ConfigurationSettings.AppSettings.Get("MySetting")

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

我读到我应该使用:

ConfigurationManager.AppSettings["MySetting"]

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

最好的方法是什么?


当前回答

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

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

其他回答

我总是为所有配置值创建一个带有类型安全属性的IConfig接口。然后,Config实现类将调用包装到System.Configuration。整个系统。配置调用现在在一个地方,维护和跟踪正在使用的字段并声明它们的默认值变得更加容易和清晰。我编写了一组私有帮助器方法来读取和解析常见数据类型。

使用IoC框架,你可以通过简单地将接口传递给类构造函数,在应用程序中的任何地方访问IConfig字段。你还可以在你的单元测试中创建IConfig接口的模拟实现,这样你就可以测试各种配置值和值组合,而不需要触及你的App.config或Web。配置文件。

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

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

为了完整起见,还有另一个选项只适用于web项目: System.Web.Configuration.WebConfigurationManager.AppSettings(“MySetting”)

这样做的好处是不需要添加额外的引用,因此对某些人来说可能更可取。

我使用的是Mac版本17.0.6的Visual Studio。

正如你在这张截图上看到的,不可能给System.Configuration添加引用。

解决方案:

安装NuGet Package - System.Configuration.ConfigurationManager 创建app.config文件,将“Build action”设置为“EmbeddedResource”

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <appSettings>
        <add key="name" value="Joe"/>
    </appSettings>
</configuration>

使用System.Configuration; 享受)

string name = ConfigurationManager.AppSettings["name"];

BTW:不要为库添加app.config