2011-12-29 4 views
1

私はapp.configファイルにいくつかの異なるセクションに値を格納しています。私はこれらのスニペットを持っています:codebehindからapp.configのカスタムセクションを読むにはどうすればよいですか?

<configuration> 
    <configSections> 
    <sectionGroup name="someDataAccessLayer"> 
     <section name="databaseConnectionStrings" type="sometype" /> 
    </sectionGroup> 
    </configSections> 
    <someDataAccessLayer> 
    <databaseConnectionStrings> 
     <databaseConnectionString name="someSQL"   
      value="database=somedatabase;Integrated Security=False;User Id=sa;server=someserver;Password=somepassword/> 
    </databaseConnectionStrings> 
    </someDataAccessLayer> 

コードビハインドでどのように接続文字列を読みますか?具体的にはvalue

database=somedatabase;Integrated Security=False;User Id=sa;server=someserver;Password=somepassword 

ありがとうございます!質問がまだ不明な場合はお知らせください。

答えて

1

あなたの構成セクションがそれを処理するために、いくつかの.NETクラスに関連付けられます。

<configSections> 
    <sectionGroup name="someDataAccessLayer"> 
     <section name="databaseConnectionStrings" type="sometype" /> 
    </sectionGroup> 
    </configSections> 

ので<localeSettings>セクションから設定を読み取るために、あなたはConfigurationManagerは(あなたにSystem.Configurationへの参照を追加使用する必要がありますそのクラスのインスタンスにそれらの設定を取得するためのプロジェクト):

sometype cs = ConfigurationManager.GetSection("someDataAccessLayer/databaseConnectionStrings") as  sometype; 

今、あなたはそのconfigセクションのすべての設定が含まれているタイプsometypeのオブジェクトを持っています。これらのプロパティの1つは、データベース接続文字列のリストになります。これにより、列挙して適切なものを見つけて、.Valueプロパティを読み取ることができます。

+0

感謝の絞りかすを。これは助けになった。 – will0809

+0

@marc_sも条件付きで更新できますか? – King

0

app.configをセッティング:

<configuration> 
     <configSections> 
     </configSections> 
     <connectionStrings> 
      <add name="MyApp.LocalConnectionString" 
       connectionString="Data Source= .\SQLEXPRESS;Initial Catalog=DBName;Integrated Security = true" 
       providerName="System.Data.SqlClient" /> 

ConfigurationManagerとして使用してDataLayerのアクセス:

// add reference 
using System.Configuration; 
// then access connection string in your class 
private static string strConnectionString = ConfigurationManager.ConnectionStrings["MyApp.LocalConnectionString"].ConnectionString; 
関連する問題