ConfigurationManager 返回 null 而不是字符串值

发布于 2024-10-05 07:33:28 字数 1079 浏览 3 评论 0原文

我试图从存储在工作目录中的 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>

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

I am trying to retrieve values from my App.config file which is stored in my working directory, however when I run the program it returns null. I am very confused why this is so, and have looked over the code many times in an attempt to spot an error.

Here is my App.config file code:

<?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>

Here is my C# code:

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;

      ...

When I run this code, p = null and c = null.

I have referenced System.Configuration.dll.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

ゝ杯具 2024-10-12 07:33:28

您是否确保配置文件正确放置在运行应用程序的目录中?该目录中实际上有一个名为.exe.config 的文件吗?

我只是在这里猜测 - 也许您在不同的项目中添加了 App.Config 文件,然后是您的 exe 程序集项目...?

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

希望这有帮助,

Ran

Did you ensure that the config file is placed correctly at the directory from which you're running the application? Is there actually a file called <app name>.exe.config in that directory?

I'm just guessing here - maybe you added the App.Config file in a different project then your exe assembly project...?

By the way, I copied your code and App.Config as is to a clean project, and this code worked for me. So I'd look in the direction of the config file itself and not in the code. The code is fine...

Hope this helps,

Ran

梦幻的味道 2024-10-12 07:33:28

如果您的配置文件在不同的类库中使用,则必须更改名称YourClasslibraryDllname.dll.config,并且必须更改配置文件复制到输出目录 property

Ex:
   YourSolution
       ClassLibrary_1
            ClassLibrary_1.dll.config
            ApplicationConfigurationReader.cs
            ConfigurationConst.cs
       ClassLibrary_2
       ConsoleApp
  1. 像这样重命名您的配置文件 YourClasslibraryDllname.dll.config
  2. 打开属性窗口
  3. 不复制更改为始终复制

在此处输入图像描述

  1. 添加参考->组装-> System.Configuration

  2. 在 ClassLibrary_1 项目中添加以下类

ConfigurationConst 类 使用 System.Configuration;

public static class ConfigurationConst
{
   public static KeyValueConfigurationCollection Configs;
}

ApplicationConfigurationReader 类 使用 System.Configuration;

internal class ApplicationConfigurationReader
    {
        public void Read()
        {
            // read assembly
            var ExecAppPath = this.GetType().Assembly.Location;

            // Get all app settings  in config file
            ConfigurationConst.Configs = ConfigurationManager.OpenExeConfiguration(ExecAppPath).AppSettings.Settings;

        }
    }

使用 ClassLibrary_1 读取配置;

static void Main(string[] args)
{
    new ApplicationConfigurationReader().Read();
    var Configval = ConfigurationConst.Configs["provider"].Value;            
    Console.ReadKey();
}

我希望你能得到干净的帮助

If your config file use in different class library you must change your name YourClasslibraryDllname.dll.config and you must change config file copy to output directory property

Ex:
   YourSolution
       ClassLibrary_1
            ClassLibrary_1.dll.config
            ApplicationConfigurationReader.cs
            ConfigurationConst.cs
       ClassLibrary_2
       ConsoleApp
  1. Rename your config file like this YourClasslibraryDllname.dll.config
  2. Open Properties Window
  3. Change Do Not Copy to Copy Always

enter image description here

  1. Add reference -> Assembly -> System.Configuration

  2. Add below clases in ClassLibrary_1 Project

ConfigurationConst Class using System.Configuration;

public static class ConfigurationConst
{
   public static KeyValueConfigurationCollection Configs;
}

ApplicationConfigurationReader class using System.Configuration;

internal class ApplicationConfigurationReader
    {
        public void Read()
        {
            // read assembly
            var ExecAppPath = this.GetType().Assembly.Location;

            // Get all app settings  in config file
            ConfigurationConst.Configs = ConfigurationManager.OpenExeConfiguration(ExecAppPath).AppSettings.Settings;

        }
    }

Read Config using ClassLibrary_1;

static void Main(string[] args)
{
    new ApplicationConfigurationReader().Read();
    var Configval = ConfigurationConst.Configs["provider"].Value;            
    Console.ReadKey();
}

i Hope you can get clean help

小…红帽 2024-10-12 07:33:28

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

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="ClientSettingsProvider.ServiceUri" value="" />
  </appSettings>
</configuration>

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

In Case all the settings are correct but still if you get null values, Please check your app.config file and replace the xml code as below,

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="ClientSettingsProvider.ServiceUri" value="" />
  </appSettings>
</configuration>

Now Run your Code, you might see the proper values

你げ笑在眉眼 2024-10-12 07:33:28

如果调试文件夹中有 .dll,请将配置文件重命名为 yourprojectname.dll.config。这对我来说有效

If you have .dll in your debug folder, then rename your confif file to yourprojectname.dll.config. This worked in my case

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文