Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to get the Connection String from App.config

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 354
    Comment on it

    To get the connection String from App.config, we will proceed as follows:-

     

    1. First we need to add the connection string in App.config file.

     

    Example:

    <configuration>

       <connectionStrings>

              <add name="ConString" connectionString="DataSource=(local);Initial Catalog=StudentRecord;Integrated Security=true" />

       </connectionStrings>

    </configuration>

     

    2. Now we would need to include a System.Configuration reference in our application using following steps:

     

          2.a. Open the Solution Explorer and right click on References folder, after that select “Add Reference” option from the context menu.

     

     

     

         2.b. Clicking “Add Reference” pops up Reference Manager window, where we will select System.Configuration assembly and click on OK.

     

        

    2.c. To check whether the reference of System.Configuration is added or not, explore the References node in Solution Explorer.

     

      

     

    3. Having added Reference in our project, now we need to add its reference in the code file where we want to access connection string defined in App.Config. Here reference will be added using corresponding namespace in C# code file.

     

    Syntax to add Namespace:

    using System.Configuration;

     

    Syntax to get connection string:

    var connectionString=ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;

     

    A sample C# code to illustrate this example

     

    App.config Code:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <startup> 
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
        </startup>
      <connectionStrings>
        <add name="ConString"
        connectionString="Data Source=(local);Initial Catalog=EmployeeRecord;Integrated Security=True"/>
      </connectionStrings>
    </configuration>

     

    C# Code:

    using System.Windows.Forms;
    using System.Configuration;
    
    namespace AppConfigString
    {
       public partial class Form1 : Form
        {
          string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
           public Form1()
            {
               InitializeComponent();
            } 
         }
     }

     

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: