Get connection string from app.config file


  • How do i read my connection string from app.config file ?
    I also know that connection string is saved in settings.settings, but i don't know how to get value from there either (I found info about this only for vb, not for c#)

    Here is the app.config file:

    <?xml version="1.0" encoding="utf-8" ?>
            <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
                <section name="_4UnitTesting.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" />
            <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
                <section name="_4UnitTesting.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
            <add name="_4UnitTesting.Properties.Settings.DBConnectionString"
                connectionString="Data Source=mix1;Initial Catalog=DB;Integrated Security=True"
                providerName="System.Data.SqlClient" />
            <_4UnitTesting.Properties.Settings />
            <_4UnitTesting.Properties.Settings />

    Saturday, November 26, 2005 9:18 AM


  • What I had to do to get mine to work in VS2005.

    Just declaring the System.Configuration is not enough. I had to Add Reference>System.Configuration.DLL after that the error "ConfigurationMananger is not declared" went away.

    Imports System

    Imports System.IO

    Imports System.Configuration

    Module FileCleanup

    Dim FileName As String

    Dim FilePath As String = ConfigurationManager.AppSettings("FilePath")

    Wednesday, December 07, 2005 6:46 PM

All replies

  • Hi,

    look at this code on how to get information from a aapplication.config file.

    They show it with a title and a connection string.
    • Proposed as answer by robinson cruso Tuesday, December 22, 2009 12:12 AM
    Saturday, November 26, 2005 12:03 PM
  • Article suggests to use


    in order to get connection string, but compiler says "This method is obsolete, it has been replaced by ConfigurationManager.AppSettings"

    I tried this manager but ir won't work either... :(

    anyone can suggest anything else ?

    Saturday, November 26, 2005 8:50 PM
  • Hmm,

    thats strange how can a propety be obsolete, if its new in .net 2.0.

    Note: This property is new in the .NET Framework version 2.0.

    from MSDN

    Has anyone from MS an idea ??

    But it works, I woud ignore the message and use it until you know further details.
    Sunday, November 27, 2005 10:09 AM
  • Hi,

    Can you be more specific when you say, the ConfigurationManager wont work ?

    The code snippet below shows the usage of the ConfigurationManager class:

    string strConnectionString=ConfigurationManager.AppSettings["ConnectionString"];


    Note that you will need to add a Reference explicitly to the System.Configuration.DLL assembly for the ConfigurationManager and add a using directive for System.Configuration for the class to be available to you.

    • Proposed as answer by igby_ Friday, March 11, 2011 9:25 AM
    Sunday, November 27, 2005 11:38 AM
  • This code did not work for me, it does not return a string. Here's what worked for me with vs 2005/.net 2.0:

    string str = ConfigurationManager.ConnectionStrings["theConnStrName"].ConnectionString;

    where "theConnStrName" is from app.config file:

    add name="theConnStrName" etc...

    Friday, December 02, 2005 4:33 AM
  • Sorry my bad english. English is not my native language.
    On VS 2005 you access app.config this way:

             dim the_name_of_the_thing as string = "este_parametro"
             dim the_value_of_the_thing as string = ""
             the_value_of_the_thing = My

    On app.config you can see a section like this:

             <setting name="este_parametro" serializeAs="String">

    That's all you have to do.
    Friday, December 02, 2005 6:26 PM
  • It's still not working for me... CondigurationManager is not even recognized as a class although i have added

    using System.Configuration; line

    I get "ConfigurationManager does not exist in the current context message"

    why is that ?

    this is the code i want to work:

    using System;

    using System.Collections.Generic;

    using System.Text;

    using System.Configuration;

    using System.Data.SqlClient;

    using System.IO;


    namespace myMoney



        class DB


            const string connectionSting = ConfigurationManager.ConnectionStrings["myMoney.Properties.Settings.myMoneyConnectionString"].ConnectionString;


            public static string GetSingleValue(string queryString)


                object queryResult;


                using (SqlConnection connection = new SqlConnection(



                    SqlCommand command = new SqlCommand(queryString);

                    command.Connection = connection;



                    queryResult = command.ExecuteScalar();


                    return queryResult.ToString();




            public static void WriteSingleValue(string updateString)


                using (SqlConnection connection = new SqlConnection(connectionSting))


                    SqlCommand command = new SqlCommand(updateString);

                    command.Connection = connection;










    Saturday, December 03, 2005 6:28 PM
  • I need this thing on C#/.NET 2.0 not vb
    • Proposed as answer by sendami Monday, January 19, 2009 5:58 PM
    Sunday, December 04, 2005 4:57 PM
  • I am having the exact same problem with getting any appSetting from the config file.  The code completion only supports the dotnet 1.x objects but the compiler fails on the with errors requiring dotnet 2.0 objects.  This is a fresh install of 2.0.  Wonder if there is a dependency on 1.x runtime for this code to compile, or VS is just flaky.  I can post a bunch of sample code, but it is all using unsupported interfaces on a clean VS 2005 install since the 2.0 interfaces do not compile.  Help MS!
    Monday, December 05, 2005 7:46 PM
  • I have sorted out at least some of the problem. If you let VS create your connection string in app.config, it's a multi-node name. Be sure to use the entire name in your reference thus:

    private static string conStr = ConfigurationManager.ConnectionStrings["DALforDaily.Properties.Settings.DSNT"].ConnectionString;

    Also note that the string must be static, or when you use it to instantiate the Db connection, the compiler complains. At this point, I am getting the desired value into the string - but so far, trying to use it is not working. I get a message that I have an "invalid argument", not terribly informative...


    Tuesday, December 06, 2005 7:22 PM
  • What I had to do to get mine to work in VS2005.

    Just declaring the System.Configuration is not enough. I had to Add Reference>System.Configuration.DLL after that the error "ConfigurationMananger is not declared" went away.

    Imports System

    Imports System.IO

    Imports System.Configuration

    Module FileCleanup

    Dim FileName As String

    Dim FilePath As String = ConfigurationManager.AppSettings("FilePath")

    Wednesday, December 07, 2005 6:46 PM
  • I am using the connection string and it works excelent for me.

    Its very simple :)

    you can Import the Connection string which resides in Project Settings.

    string str= Properties.Settings.Default.myConnectionString;


    let me past all of my code for LoaddataBase() function so it can  explain how can one use the DataTable also. This is enhanced version of the older DataTable object.

    I am populating  Listbox from my the Table object below.

    private void LoadDataBase(){



           DataTable myTable = new DataTable("myTable");

    using (OleDbConnection conn = new OleDbConnection(Properties.Settings.Default.myConnectionString)){

         OleDbCommand cmd = new OleDbCommand
                                       (@"SELECT Tasks.FullTaskName   FROM Tasks", conn);

        OleDbDataReader rd = cmd.ExecuteReader();
        //this was only possible with DataSet object earlier ----Cool eh ;)

    foreach (DataRow row in myTable.Rows){

    TreeNode node = new TreeNode(row[0].ToString());


    this._TreeView.Sorted = true;





    catch (OleDbException e){

    MessageBox.Show("Error: {0}" + e.Errors[0].Message);




    Did it help? mark it!

    • Proposed as answer by c-sharp-coder Monday, April 05, 2010 5:54 PM
    Wednesday, December 07, 2005 8:14 PM
  • 1.



    object value = Properties.Settings.Default.<xxx>

    Thank you !!!

    Search Keys: configSections, sectionGroup, applicationSettings, setting, name, serializeAs, connectionStrings, providerName, System.Data.SqlClient

    Wednesday, January 11, 2006 1:36 PM
  • AppSettings is obsolete.  ClientSettingsSection is the new way (for Windows Forms client applications). 

    I have a problem with my code.  I am trying to save a value to the client settings area. 

    ClientSettingsSection css = new ClientSettingsSection();

    css.Settings.Get(edURL.Name).Value = edURL.Text;

    Error 1 Cannot implicitly convert type 'string' to 'System.Configuration.SettingValueElement' 

    I need an example of how to do it right


    Friday, February 17, 2006 9:28 PM
  • Almost a year later, I find myself struggling with the same thing.

    Just an additional bit of info, for anyone else out there that is still learning this, You need to Add Reference and browse to System.Configuration.dll even though you already have a reference to System.Configuration.dll then it works.

    Sunday, May 14, 2006 5:23 AM
  • I had the same problem and was almost going to reply with the same solution.  I finally saw this last post on the second page of posts. 

    Thanks for posting your solution.  It's the only one that made since...and worked.


    Thursday, June 01, 2006 5:45 PM
  • Very strange, how it should work (in is this:


    oConn = New SqlConnection(configurationmanager.ConnectionStrings("connWorkflowTracking").ConnectionString.ToString)


    I manually added the connection strings to the app.config file and this works great for me in one project (Windows Workflow Sequential Library), but it doesn't work in another project of the same type. I get an "object reference not set to an instance of an objec" error. What the hell??? How could it work in one project and then not work in basically another identical project????


    Sunday, April 01, 2007 6:20 PM
  • lol..although I woudn't go so far as to say that makes sense it did work. Thanks for the answer!



    Monday, April 02, 2007 4:21 PM
  • Thx buddy.. this worked for me......


    But can u pls tell me even after using "using System.Configuration" statement, we have

    to add explicit reference to System.Configuration DLL ??


    Thx in advance....

    Friday, June 01, 2007 6:47 AM
  • Yes You need to add reference of System.Configuration.dll explicitly to get rid of the error. I too did the same way.




    Friday, June 15, 2007 2:53 PM

    just use the auto generated code:



    string connectionstring = global::WindowsApplication1.Properties.Settings.Default.ASPNETDBConnectionString;


    don't know how but this works.

    Thursday, June 21, 2007 2:31 AM
  • I have read this thread top to bottom.  Thanks to all those who contributed.  I added a reference to the System.Configuration.dll, which got rid of the "configurationManager not declared" error, and I added "Imports System.Configuration" to the top of the code behind.  I now have this:



    Imports System.Data

    Imports System.Data.SqlClient

    Imports System.IO

    Imports System.Configuration


    Public Class Form1


    Private cn As New SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("StorkConnection").ConnectionString)





    But now, on the line "Private cn As New SqlClient..." I get this error: "An error occurred creating the form. See Exception.InnerException for details.  The error is: Object reference not set to an instance of an object."


    This is the XML in the app.config:



    <?xml version="1.0" encoding="utf-8" ?>



    <add name="StorkConnection" connectionString="Data Source=xxxx; Initial Catalog=Stork; Persist Security Info=True; User ID=xxxx; Password=xxxx; Asynchronous processing = true " providerName="System.Data.SqlClient" />






    I am out of ideas!!!



    Tuesday, June 26, 2007 7:48 PM
  • NOTE FOR ALL....


    If you're getting errors compiling while using ConfigurationManager in the .NET 2.0 framework then right click on references and explicitly add the .NET 2.0 version of System.Configuration.


    This will resolve problems with it not being able to find the ConfigurationManager class.


    Hope that helps.

    Thursday, June 28, 2007 10:31 AM
  • HOW?  In the name of all that's holy HOW?

    I've had this problem since my first .Net 2 program. It's so intractible that I've created a webservice that assembles connection strings from field/value tables in a database and returns them to me.

    I've added reference to System.Configuration, I've browsed to the System.Configuration.DLL file and NOTHING WORKS! Three years and NO SOLUTION. 

    Thursday, January 10, 2008 9:09 PM



    In order to get the connection string in app.config file.


    Firstly, you need to add System.Configuration to your references folder.

    Secondly, now you only can use ConfigurationManager in your code.


    Correct me if I am wrong.





    Saturday, February 23, 2008 8:11 AM
  • Just use:

    It is working for the default app.config file.
    Code Snippet

    <?xml version="1.0" encoding="utf-8" ?>
    <add name="PROJECT_NAME.Properties.Settings.PROJECT_NAMEConnectionString"
    connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\database.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"providerName="System.Data.SqlClient"/>

    Sunday, April 06, 2008 8:33 PM
  •   string connectionString = ConfigurationManager.ConnectionStrings[1].ToString();
    Wednesday, July 09, 2008 8:39 PM

    i don't know what happens here with the configurations and stuff but i usually just use



    i.e. in code

    Dim sCnn As SqlClient.SqlConnection = New SqlClient.SqlConnection(My.Settings.wsConnectionString)


    in app.config






    <add name="WindowsApplication1.My.MySettings.wsConnectionString"

    connectionString="Data Source=xxx;Initial Catalog=ws;Integrated Security=True"

    providerName="System.Data.SqlClient" />


    Monday, October 13, 2008 5:16 AM
  • Solution :


      1.- Add the reference in the Application Properties to the System.configuration.dll Namespace

          ( to don’t have compilation errors like "ConfigurationManager not defined" )

      2.- Import the Namespace in your code with the "Imports System.Configuration"

      3.- Instantiate the ConnectionStringSettings with the New keyword (is a Class)

      4.- Use the string variable to your connection.


    Code (One Form with One Button to test it) :


    Imports System.Configuration


    Public Class MyClass


       Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

          Dim settings As New ConnectionStringSettings

          Dim strMyString As String

          settings = ConfigurationManager.ConnectionStrings("MyConnName")

          strMyString = settings.ConnectionString.ToString


       End Sub


    End Class


    Wednesday, November 05, 2008 12:05 AM
  • The MSDN Library

    ( With a little modification to include in a module )


    Imports System.Configuration

    Module SharedModules


       '  Retrieves a connection string by name.

       '  Returns Nothing if the name is not found.

       Public Function GetConnectionStringByName(ByVal name As String) As String


          ' Assume failure

          Dim returnValue As String = Nothing


          ' Look for the name in the connectionStrings section.

          Dim settings As ConnectionStringSettings = _



          ' If found, return the connection string.

          If Not settings Is Nothing Then

             returnValue = settings.ConnectionString

          End If


       Return returnValue


    End Function


    End Module



    References to MSDN Library


    Connection String Syntax (ADO.NET)


    Connection Strings and Configuration Files (ADO.NET)


    Encrypting Configuration File Sections Using Protected Configuration


    Wednesday, November 05, 2008 4:05 PM
  • Hello,

    This topic is old but I am posting an answer for those who need the information in future.

    You can read your connection string by specifying it into the Configuration Manager's connection strings collection like this:

    in the configuration file:

        <add name="dbConnection" connectionString="Data Source=localhost\sqlexpress;Initial Catalog=testDB;Integrated Security=True;Pooling=False" providerName="System.Data.SqlClient"/>


    in the source code:

    string connString = ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;

    If you have the name of the connection string in a variable you don't have to put the variable in quotes. In the above posts I saw examples like:

    ConfigurationManager .ConnectionStrings[ "AppName.Properties.Settings.ConnStr" ].ConnectionString

    this is wrong. I guess that the guy wanted to access the string from the application settings, he just had to remove the " " and everything will work.
    or another example:
    string connectionKey = "dbConnection";

    the retrieve of the connection string will be like this:
    string connString = ConfigurationManager.ConnectionStrings[connectionKey].ConnectionString;

    In case you want to get all the connection strings you can iterate the ConfigurationManager.ConnectionStrings collection. You can digits as index, not only names. For example

    for (int i=0; i<ConfigurationManager.ConnectionStrings.Count; i++)

    ConfigurationManager.ConnectionStrings is a collection of type ConnectionStringSettingsCollection, so ConfigurationManager.ConnectionStrings[i] will return ConnectionStringSetting object. This way you can find some more information for the connection string which you can find helpful.

    There is one drawback here. ConfigurationManager.ConnectionStrings will return not only the connection strings in you app.config file, but also from the machine.config file. It seems that the ConfigurationManager joins the current config with the one of the whole machine.

    But yet it is possible to open any config file, get the connectionStrings section, parse it and get the necessary information. You can also check the GetSection () method of the ConnectionManager class.

    Enjoy :)
    Friday, April 17, 2009 6:13 AM

  • Conf. File:






    add name="INow_Bank_Rec.My.MySettings.scidatasqlConnectionString"



    connectionString="Data Source=dbserver;Initial Catalog=...;Persist Security Info=True;User ID=sa;Password=...."



    providerName="System.Data.SqlClient" />




    Getting Connection string In code



    sqlCon As String = My.Settings.scidatasqlConnectionString

    Wednesday, May 27, 2009 9:55 PM
  • I remember stumbling over this many years ago, one other thing that I found recently was that I got the same error on the configurationManager line I originally had, even though I had added the configuration.dll with Add Reference...

    I just did the Add Reference again and the error went away... even though looking at properties of the references file showed no change, the same .net 2.0 version.. Wierds

    Sunday, July 12, 2009 1:40 PM
  • Hi,

    after trying all the other solutions, this one really worked!

    Thursday, August 27, 2009 5:37 AM
  • try this
    <project name>.Properties.Settings.Default.<connection string>;

    Thursday, January 14, 2010 8:56 PM
  • I have always used this and it works like magic :-)



    reader = new AppSettingsReader();


    string myConnectionString = (String)reader.GetValue("ConnectionString", String.Empty.GetType());

    Monday, April 19, 2010 10:24 AM
  • I think you will have to add a Reference to System.Configuration

    Hope this post is useful...


    Monday, August 02, 2010 7:47 PM
  • Its really funny to discover that adding just a System.Configuration.dll as refernce would solve the problem..It really helped me out:)


    Tuesday, September 07, 2010 6:08 AM
  • I remember stumbling over this many years ago, one other thing that I found recently was that I got the same error on the configurationManager line I originally had, even though I had added the configuration.dll with Add Reference...

    I just did the Add Reference again and the error went away... even though looking at properties of the references file showed no change, the same .net 2.0 version.. Wierds

    I had the same problem... couldn't find any solution until i read this post ! It works ! Thx.

    Wish i could understand why do we had to add this ref ...

    Thursday, September 16, 2010 9:22 AM
  • alternatively you can also use:

    string conStr = global::Solution1.Properties.Settings.Default.ConnectionStringName;

    Sohaib Ahmad [Business Management Solution Professional]


    Saturday, November 20, 2010 12:23 PM
  • The Solution is simple . You need to Just add reference to the Sysin

    tem.Configuration dll present GAC.

    Best Regards

    Friday, April 01, 2011 4:57 PM


    First of all you have to add "System.Configuration" file to References of your Project you can find "System.Configuration" under the ".NE"T tab when you right click on "References" and say "Add"

    Then you have to include "System.Data.SqlClient" library with the code "using"

    Then again with the code "using" add System.Configuration library

    after doing those you can go on with the code below

    SqlConnection conn = new SqlConncetion(ConfigurationManager.ConnectionStrings["nameOfYourConnectionString"].ConnectionString);


    Have nice day you can ask anytime.

    Özgür TEZEL
    • Proposed as answer by cingalls Wednesday, April 27, 2011 3:42 PM
    Thursday, April 21, 2011 9:16 AM
  • Small typo:
    SqlConnection conn = new SqlConncetion(ConfigurationManager.ConnectionStrings["nameOfYourConnectionString"].ConnectionString);

    Should be:
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["nameOfYourConnectionString"].ConnectionString);


    Afer, as noted by Tezel, adding System.Configuration reference, and
    using System.Configuration;
    using System.Data.SqlClient;

    I created the following WORKING connection (see my app.config file below):
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Wpf_View_DataTable1.Properties.Settings.NORTHWNDConnectionString"].ConnectionString);

    ===== My app.config ================================================
    <?xml version="1.0" encoding="utf-8"?>
    add name="Wpf_View_DataTable1.Properties.Settings.NORTHWNDConnectionString"
    connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename =&quot;C:\Data\MCPD Training\Northwind\NORTHWND.MDF&quot;;Integrated Security=True;Connect Timeout=30;User Instance=True"


    Thanks Tezel for the answer.

    Wednesday, April 27, 2011 3:55 PM
  • "ConfigurationManager does not exist in the current context message" shows because you still do not have a reference to the System.Configuration

    Try This:

    1. In the Solution explorer window, Right-Click on the Project

    2. click on "Add Reference..."

    3. In the Add Reference window, in the .NET tab, find and select "System.Configuration" and click OK


    This should solve your problem

    Saturday, August 13, 2011 5:05 PM
  • nyce, thanx
    Tuesday, May 22, 2012 7:46 PM
  • THIS is what finally did it for me! Thank you! (I know this is an ancient thread but this was driving me crazy)
    Monday, June 24, 2013 3:53 PM