2013-08-19 60 views
0

我讀了許多與配置管理器相關的主題,但無法解決問題。我只想讀取連接字符串以及Web應用程序中CLASS LIBRARY的一些appsetting鍵。c#中的ConfigurationManager有什麼問題嗎?

我引用了System.Configuration類。

這是我的代碼

using System.Configuration; 

... 

string constr = ConfigurationManager.ConnectionStrings["cbuddydb"].ConnectionString; 
string strUserName = ConfigurationManager.AppSettings["username"]; 
string strPwd = ConfigurationManager.AppSettings["password"]; 

但似乎從一個不同的配置文件讀取。而不是從我的項目中的web.config。因爲讀出的值是錯誤的

請正確的代碼 編輯幫助:web.config中以下

<configuration> 
    <system.web> 
     <compilation debug="true" targetFramework="4.0" /> 
    </system.web> 
    <system.data> 
    <connectionStrings> 
     <clear /> 
     <add name="cbuddydb" connectionstring= 
      "Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=myDataBase;Persist Security Info=True; 
      [email protected];[email protected];Option=3" providerName="MySql.Data.MySqlClient" password=""/> 
    </connectionStrings> 
    <appSettings > 
     <clear /> 
     <add key="username" value ="6/0RUNnSmUBsbdNoCg+9Sw=="/> 
     <add key="password" value =""/> 
    </appSettings> 
    </system.data> 
</configuration> 
+1

也許你對調試/發佈有一些轉換? – wudzik

+2

請發佈您的web.config,以及您的實際和預期結果。 –

+3

在.NET配置系統中,** by design **,'ConfigurationManager'總是從**託管應用程序的**配置文件中讀取 - **從類庫自己的單獨文件中讀取**。如果您需要爲您的類庫配置設置 - 您必須將它們放到使用您的類庫的應用程序的'app.config'或'web.config'中 –

回答

4

這樣做的原因是因爲配置文件的繼承。索引爲0的連接字符串可能不在您的配置文件中,但可能已從machine.config繼承。查看ASP.Net配置文件的層次結構和繼承:http://msdn.microsoft.com/en-us/library/ms178685.aspx

您可以清除繼承的連接在你的web.config

<connectionStrings> 
    <clear /> 
    <add name=」MyConnString」 connectionString=「Whatever「 /> 
    </connectionStrings> 

編輯指定以下字符串:在你的配置,將您的ConnectionStrings和標籤的appSettings直接的配置元素下方。它們不應該在system.data元素中。它們是配置元素的直接子節點。並在providerName後面刪除額外的密碼屬性。我無法驗證您的連接字符串,因爲我不知道您是如何使用它的。

<configuration> 
    <connectionStrings> 
    <clear /> 
    <add name="cbuddydb" connectionString= 
     "Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=myDataBase;Persist Security Info=True; 
     [email protected];[email protected];Option=3" providerName="MySql.Data.MySqlClient"/> 
    </connectionStrings> 

    <appSettings >   
    <add key="username" value ="6/0RUNnSmUBsbdNoCg+9Sw=="/> 
    <add key="password" value =""/> 
    </appSettings> 

    <system.data> 
.... 

你應該考慮在你的配置文件加密敏感信息,如密碼。

+0

謝謝@Reubz我加了。我也從索引更改爲名稱,但錯誤是「對象引用未設置」。 – sjd

+0

ConfigurationManager在不屬於aspx項目的解決方案中的類庫中調用。那是問題嗎?另外我注意到web.config附近有一個web.Debug.config和web.release.config文件。不確定何時使用。 – sjd

+0

@ user1616785看到我的編輯 – Riv