2012-03-25 17 views
5

私はこのコードを使用してapp.configファイルから接続文字列を読み取っていますが、常にnull値を返します。私のApp.configファイルは私のプロジェクトの下にあります。どちらの方法は、null値を結果としてされていますC#でApp.configファイルから接続文字列を読み取る方法

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <connectionStrings> 
    <add name="dbConn" providerName="System.Data.SqlClient" 
      connectionString="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User Id=sa;Password=123" /> 
    </connectionStrings> 
</configuration> 
+0

プロジェクトが*クラスライブラリ*プロジェクトことが起こるのか?.....一つのクラスでの接続文字列を定義し、その文字列を呼び出しますかそれらは実際には自分の 'app.config'ファイルを使用しません**あなたのクラスライブラリを使ってあなたの接続文字列を**ホスティングアプリケーション**(メインプログラムまたはWebアプリケーション/ Webサイト)に入れる必要があります –

+0

marc_s ++は私のために働いた.. –

答えて

4

あなたは第二の方法を使用すると

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <connectionStrings> 
    <add name="dbConn" providerName="System.Data.SqlClient" 
      connectionString="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User Id=sa;Password=123" /> 
    </connectionStrings> 
    <appSettings> 
    <add key="dbConn" value="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User Id=sa;Password=123" /> 
    </appSettings> 
</configuration> 

を試してみてくださいすることができ:

public SqlConnection getConnection() 
{ 
    try 
    { 
     // connectionString = ConfigurationManager.AppSettings["dbConn"]; 

     connectionString = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString; 
     connectionString = System.Configuration.ConfigurationManager.AppSettings["dbConn"]; 
     sqlConnection = new SqlConnection(connectionString); 

     sqlConnection = new SqlConnection(connectionString); 
    } 
    catch (Exception ex) 
    { 

    } 
    return sqlConnection; 
} 

これは私のapp.configファイルの宣言です。

ソリューションエクスプローラでApp.Configファイルを選択し、プロパティウィンドウでCopy to Output DirectoryCopy Alwaysを選択してください。今すぐアプリケーションをビルドし、もう一度やり直してください。

See the screenshot

+1

はまだnullを返します – Kalanamith

+0

上記の私の編集を参照してください。 – PraveenVenu

5

私はあなたが右のそれを行う第一、あなたは二回、接続文字列を読み取ろうあなたの問題を考えると、あなたがそれを行う二回目は間違っているので、ちょうど二行目を削除します。

connectionString = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString; 
sqlConnection = new SqlConnection(connectionString); 

ConfigurationManager.AppSettings設定の<appSettings>...</appSettings>セクションにアクセスするために使用されます。

+0

ここではそうではありません。 – Kalanamith

+0

あなたはそれを再割り当てしてconnectionStringを上書きしています。 connectionStringの2番目のassigmentを削除しても問題ありません。 – Jay

+0

私は彼に何を書きましたか。彼はそれが働いていないと言います。 –

1

あなたは、単純な

public class Connection 
    { 
     /// <summary> 
     /// Connection String 
     /// </summary> 
     public static string ConnectionString 
     { 
      get 
      { 
       return ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString; 
      } 
     } 
    } 

//Returning connction string 
sqlConnection conn = new SqlConnection(Connection.ConnectionString); 
1
connectionString=global::myProject.Properties.Settings.Default.myConnectionString 
+0

私にとって運がない。 – Kalanamith

関連する問題