Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
806 views
in Technique[技术] by (71.8m points)

c# - ConfigurationManager return null instead of string values

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...