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

我发现

ConfigurationSettings.AppSettings.Get("MySetting")

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

我读到我应该使用:

ConfigurationManager.AppSettings["MySetting"]

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

最好的方法是什么?


当前回答

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

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

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

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

using System.Collections.Specialized;

其他回答

更新。net Framework 4.5和4.6;以下将不再工作:

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

现在通过Properties访问Setting类:

string keyvalue = Properties.Settings.Default.keyname;

有关更多信息,请参阅管理应用程序设置。

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

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

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

这里有一个例子:App.config

<applicationSettings>
    <MyApp.My.MySettings>
        <setting name="Printer" serializeAs="String">
            <value>1234 </value>
        </setting>
    </MyApp.My.MySettings>
</applicationSettings>

Dim strPrinterName as string = My.settings.Printer

试试这个:

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

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

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

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

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