c#给出错误的Appsettings:当前上下文中不存在名称"ConfigurationManager"

Nat*_*Pet 3 .net c# configurationmanager

在我的程序的顶部,我有以下内容:

       using System.Configuration;
Run Code Online (Sandbox Code Playgroud)

在我的代码中,我有以下内容:

int  CompanyID = Convert.ToInt32(ConfigurationManager.AppSettings["CompanyId"]
    .ToString());
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

The name 'ConfigurationManager' does not exist in the current context
Run Code Online (Sandbox Code Playgroud)

我不确定我错过了什么.

tme*_*ser 11

要扩展一点,您需要添加一个引用以System.Configuration.dll使其工作.这有点误导,因为System.Configuration命名空间也存在于基础内部System.dll,并且包含一些远较少使用的对象,如SettingsContext.结果,它似乎真的应该工作,但事实并非如此.这真的令人困惑,而且目前是.NET框架中的一个迟钝的陷阱.

幸运的是,System.Configuration.dll它位于.NET基础框架中,因此您只需通过右键单击References项目中的文件夹,单击Add Reference,然后System.Configuration.NET选项卡下查找来添加引用.

将其导入项目后,请不要忘记添加using System.Configuration到要使用的代码文件的顶部ConfigurationManager.