will0809
will0809

Reputation: 237

How do I read a custom section in app.config from codebehind?

I have an app.config file that stores values in a few different sections. I have these snippets:

<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>

How do I read the connection string in the codebehind? Specifically the value which is

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

Thanks for your help! Please let me know if the question is still unclear.

Upvotes: 1

Views: 2467

Answers (2)

Niranjan Singh
Niranjan Singh

Reputation: 18290

App.Config Settings:

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

Access at DataLayer using the ConfigurationManager as:

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

Upvotes: 0

marc_s
marc_s

Reputation: 754608

Your configuration section will be associated with some .NET class to handle it:

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

So to read the settings from the <localeSettings> section, you need to use the ConfigurationManager (add a reference to System.Configuration to your project) to get those settings into an instance of that class:

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

Now you have an object of type sometype that contains all the settings in that config section. One of those properties will be a list of database connection strings, which you can now enumerate and find the appropriate one and read it's .Value property.

Upvotes: 1

Related Questions