In this article I will explain with an example, how to store and access Connection String in Windows Application (Windows Forms) using C# and VB.Net.
The Connection String will be stored (saved) in the App.Config file inside its ConnectionStrings section and later it will be read in code using the ConfigurationManager class in C# and VB.Net.
In Windows applications, Class Library or Console applications one has to reference the System.Configuration Assembly in order to read Connection String value from the App.Config file.
 
 
Adding App.Config file to the Project
In order to add the App.Config file, you will need to right click on the project and select Add option and then New Item option from the Context Menu.
How to store (save) Connection String in Windows Application (Windows Forms) using C# and VB.Net
 
Then you will need to select the Application Configuration File and click the Add button from the Add New Item dialog.
How to store (save) Connection String in Windows Application (Windows Forms) using C# and VB.Net
 
 
Adding ConnectionString to the App.Config file
You need to add the Connection String in the ConnectionStrings section of the App.Config file in the following way.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
        <add name="ConString" connectionString="Data Source=Mudassar-PC\SQL2005;Initial Catalog=Northwind;Integrated Security=true"/>
    </connectionStrings>
</configuration>
 
 
Adding System.Configuration reference
The very first thing you need to do is to add reference of the System.Configuration Assembly to the project in the following way.
1. Right click on the project and click Add Reference option from the Context Menu.
How to store (save) Connection String in Windows Application (Windows Forms) using C# and VB.Net
 
2. From the Add Reference dialog box, click on .Net Tab and look for System.Configuration assembly. Once you find it simply select and click OK.
How to store (save) Connection String in Windows Application (Windows Forms) using C# and VB.Net
 
3. Once the reference is added, it will be shown in the References folder of the Solution Explorer.
How to store (save) Connection String in Windows Application (Windows Forms) using C# and VB.Net
 
 
Namespaces
You will need to import the following namespace.
C#
using System.Configuration;
 
VB.Net
Imports System.Configuration
 
 
Reading ConnectionString from App.Config file using C# and VB.Net
Once the reference is added, you can read the Connection String value from the App.Config file in the following way.
C#
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
 
VB.Net
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConString").ConnectionString