App.Config

The following connectionString is present in App.Config

<configuration>
<appSettings>
<add key="ConnectionString" value="Data Source=machine1;Initial Catalog=database1;User Id=user1;Password=password1;"/>
</appSettings>
</configuration>

Now I would like to retrieve it using the following code
public static string GetConnectionString
{
get
{
return ConfigurationManager.AppSettings["ConnectionString"];
}
}

Is this correct
Thanks



Answer this question

App.Config

  • Dennisld

    But it returns null.

    p.s this is in .NET 2.0
    Can you see why pls
    Thanks


  • hharding

    This code can work in 2.0, that is no problem. It is only obsulated, in 2.0 you must use the ConfigurationManager class, but you still can use the ConfigutationSettings class.

    Does the ConfigurationSettings class work and is the name of the config file <executablename>.exe.config

  • KK Wong

    It is the same, only the ConfigurationSettings class is obsoleted.


  • Andrew_Shough

    Hi,

    As mentioned in the first post
    this returns null
    Thanks


  • Morg

    Hussein.Zahran wrote:
    Well the ConfigurationSettings works fine in .NET 2.0 but i really recommend the use of
    System.Configuration.ConfigurationManager.AppSettings

    As i said before, the ConfigurationSettings class is obsulated. But i was wondering if it was working with that class.

    Are you sure that the config file is located in you directory where the executable is located and the the name of the config file is <executablename>.exe.config



  • Janni J

    Yes, it is correct. Don't forget to implement exception handling when the key is missing


  • vanita

    Again, does the ConfigurationSettings class work


  • ccchai

    please note that I am using .net 2.0
    An it is not the same I don't think.

    Thanks


  • Sherif Elian

    Well the ConfigurationSettings works fine in .NET 2.0 but i really recommend the use of

    System.Configuration.ConfigurationManager.AppSettings



  • BillH

    so, how do you re-write this in .NET 2.0

    Thanks


  • Chris Cormier

    hi
    it returns null because the file that keeps the configuration it is NOT in the same directory as the main assembly. if you created the configuration file by adding it to the project it is initialy located in the base directory of your application. in order to work it must be in the DEBUG directory of the main assembly, if you are in debuging mode. If you are in the release form of the application the configuration file must be in the RELEASE directory of the main asembly.

  • Roberson

    The code that I sent initially returns null.
    So not sure what the problem is.
    Thanks

  • webGov

    I tested this, and it work like charm:


    <configuration>
    <appSettings>
    <add key="mykey" value="value" />
    </appSettings>
    </configuration>




    System.Configuration.ConfigurationSettings.AppSettings["mykey"]



  • App.Config