2010-12-01 102 views
12

我想從我的App.config文件中檢索存儲在我的工作目錄中的值,但是當我運行程序時它返回null。我非常困惑,爲什麼會這樣,並且多次查看代碼以試圖發現錯誤。ConfigurationManager返回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。

+2

是您的app.config被正確部署可執行.. IE:在執行目錄中確實存在一個'應用程序名稱。 exe.config`文件? – 2010-12-01 23:21:43

+1

App.Config是使用的模板。真正的配置文件將是「Program.Exe.Config」文件。這應該在編譯項目時完成。 – 2010-12-01 23:22:15

回答

15

您是否確保將配置文件正確放置在您運行應用程序的目錄中?該目錄中是否有一個名爲<的應用程序名稱> .exe.config?

我只是在這裏猜測 - 也許你在不同的項目中添加App.Config文件,然後你的EXE程序集項目......?

順便說一句,我將你的代碼和App.Config照原樣拷貝到一個乾淨的項目中,並且這段代碼適合我。所以我會看看配置文件本身的方向,而不是在代碼中。該代碼是好的...

希望這有助於

相關問題