ConfigurationManager返回null而不是字符串值

The*_*oss 14 .net c#

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

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

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="provider" value="System.Data.SqlClient" />
  </appSettings>
  <connectionStrings>
    <add name="connection" connectionString="Data Source=(local)\SQLEXPRESS;Initial Catalog=Autos;Integrated Security=True;Pooling=False" />
  </connectionStrings>
</configuration>
Run Code Online (Sandbox Code Playgroud)

这是我的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;

      ...
Run Code Online (Sandbox Code Playgroud)

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

我引用了System.Configuration.dll.

Ran*_*Ran 16

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

我只是在这里猜测 - 也许您在另一个项目中添加了App.Config文件,然后是您的exe汇编项目......?

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

希望这可以帮助,

  • 您不应手动复制App.config文件.它应该在构建时自动复制和重命名.也许您刚刚在项目中添加了一个名为App.config的文件,而不是添加"应用程序配置"项?您可以尝试将其重新添加到可执行项目中. (8认同)
  • **“也许您只是在项目中添加了一个名为 App.config 的文件,而不是添加“应用程序配置”项”** 是正确的答案。谢谢兰。 (2认同)