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

我发现

ConfigurationSettings.AppSettings.Get("MySetting")

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

我读到我应该使用:

ConfigurationManager.AppSettings["MySetting"]

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

最好的方法是什么?


当前回答

我使用的是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

其他回答

试试这个:

string keyvalue = System.Configuration.ConfigurationManager.AppSettings["keyname"];

在网络上。配置文件,这应该是下一个结构:

<configuration>
<appSettings>
<add key="keyname" value="keyvalue" />
</appSettings>
</configuration>

另一个可能的解决方案:

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

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

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

您可以将App.config文件添加到DLL文件中。config只适用于可执行的项目,因为所有DLL文件都从正在执行的EXE文件的配置文件中获取配置。

假设你的解决方案中有两个项目:

SomeDll SomeExe

您的问题可能与您将app.config文件包含到SomeDLL而不是SomeExe有关。SomeDll能够从SomeExe项目中读取配置。