簡體   English   中英

使用C#中的app.config文件獲取連接字符串

[英]Get connection string using app.config file in C#

我想使用app.config文件獲取連接字符串

這是我的app.config文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>    
    <add name="MSSConStr"
        connectionString="Data Source=Sithi-PC;Initial Catalog=mssdb2;User ID=XXXXX;Password=YYYYYYY"
        providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

string x = ConfigurationManager.ConnectionStrings["MSSConStr"].ConnectionString;

此語句提供異常“對象引用未設置為對象的實例”。

請你能幫我糾正這個錯誤! 這在.NET framework 3.5項目中正常工作。 但是這個項目是.NET framework 4.0。 我將參考“System.Configuration”添加到我的項目中,並在我的數據庫訪問類中使用它。 謝謝!!!

編輯 :地址代碼:

public static SqlConnection getNewConnection() 
{ 
    string x = ConfigurationManager.ConnectionStrings["MSSConStr"].ConnectionString.ToString(); 
    con2 = new SqlConnection(x); 
    return con2; 
}

有兩個可能的問題:

1)你在應用程序的其他地方有一些設置(設置,代碼等,無意中清除連接字符串(不太可能,但可能)。

2)在運行時使用的.config沒有傳播到它的連接字符串。 如果您在調試模式下運行,請打開Windows資源管理器,導航到bin / debug目錄並打開.exe.config或.vshost.exe.config文件,並查看是否在那里正確設置了連接字符串。 如果不是,請停止應用程序,清除目錄,然后重試。 如果問題仍然存在,請參閱第1項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM