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" >
<configuration>
    <configSections>
        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="_4UnitTesting.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" />
        </sectionGroup>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="_4UnitTesting.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
        </sectionGroup>
    </configSections>
    <connectionStrings>
        <add name="_4UnitTesting.Properties.Settings.DBConnectionString"
            connectionString="Data Source=mix1;Initial Catalog=DB;Integrated Security=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
    <userSettings>
        <_4UnitTesting.Properties.Settings />
    </userSettings>
    <applicationSettings>
        <_4UnitTesting.Properties.Settings />
    </applicationSettings>
</configuration>




Answer this question

Get connection string from app.config file

  • rodizzio

    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.

  • doobey

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


  • thanh dao

    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


  • bcw

    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.

    Regards,
    Vikram

  • frans poc

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

     


  • Visual Basic Fan

    Article suggests to use

    ConfigurationSettings
    .AppSettings["ConnectionString"];

    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



  • David Bridge

    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(){

           this._TreeView.Nodes.Add("Tasks");

    try{

           DataTable myTable = new DataTable("myTable");

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

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

        OleDbDataReader rd = cmd.ExecuteReader();
        myTable.Load(rd); 
        //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.Nodes[0].Nodes.Add(node);

    this._TreeView.Sorted = true;

    }

    conn.Close();

    }

    }

    catch (OleDbException e){

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

    }

    }

     




    Did it help mark it!



  • BhuttCrackSpackle

    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;< xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

    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(

                           connectionSting))

                {

                    SqlCommand command = new SqlCommand(queryString);

                    command.Connection = connection;

                    connection.Open();

     

                    queryResult = command.ExecuteScalar();

                    connection.Close();

                    return queryResult.ToString();

                }

            }

     

            public static void WriteSingleValue(string updateString)

            {

                using (SqlConnection connection = new SqlConnection(connectionSting))

                {

                    SqlCommand command = new SqlCommand(updateString);

                    command.Connection = connection;

                    connection.Open();

                    command.ExecuteNonQuery();

                    connection.Close();

                }

            }

        }

    }

     

     




  • kroyce

    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.

    http://www.codeguru.com/columns/DotNet/article.php/c7987/

  • Red Link

    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!


  • mdooley

    1.

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

    2.

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

    Thank you !!!

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


  • cgn

    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
    .Settings.Item(the_name_of_the_thing)

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

             <setting name="este_parametro" serializeAs="String">
             <
    value>15</value>
             </
    setting>

    That's all you have to do.


  • Marvy

    I need this thing on C#/.NET 2.0 not vb

  • JDArsenault

    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:

    <connectionStrings>
    <
    add name="theConnStrName" etc...


  • Get connection string from app.config file