ConfigurationManager返回null而不是字符串值

我试图从我的App.config文件中检索存储在我的工作目录中的值,但是当我运行该程序时它返回null。 我很困惑为什么会这样,并且多次查看代码以试图发现错误。

这是我的App.config文件代码:

         

这是我的C#代码:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using System.Data; using System.Data.Common; namespace DataProviderFun { class Program { static void Main(string[] args) { string p = ConfigurationManager.AppSettings["provider"]; string c = ConfigurationManager.ConnectionStrings["connection"].ConnectionString; ... 

当我运行此代码时,p = null和c = null。

我引用了System.Configuration.dll。

您是否确保将配置文件正确放置在运行应用程序的目录中? 该目录中是否存在名为 .exe.config的文件?

我只是猜测 – 也许您在另一个项目中添加了App.Config文件,然后是您的exe程序集项目……?

顺便说一下,我将你的代码和App.Config原样复制到一个干净的项目中,这段代码对我有用。 所以我会查看配置文件本身的方向而不是代码。 代码很好……

希望这可以帮助,

如果所有设置都正确但仍然获得空值,请检查您的app.config文件并替换xml代码,如下所示,

       

现在运行您的代码,您可能会看到正确的值