Site Search:
Sign in | Join | Help
4Penny.net

VB.NET

Notes, Tricks and Tips on VB.NET

June 2007 - Posts

  • Retrieving a connection string from app.config

    Retrieving a conection string from the app.config file is a pretty simple matter - but it always take me 15 minutes to find the code...

    There are two places that you can easily place config info in the app.config - the appSettings section and the connectionStrings section.

    The first thing to do is to set a reference to SYSTEM.CONFIGURATION in VB. If you don't do this, you won't be able to retrieve your code.

    appSettings:
    <configuration>
     <configSections>
    ...
        </configSections>
     <appSettings>
      <add key="live" value="somevalue" />
      <add key="dev" value="some other value" />
     </appSettings>

    Be sure that you place your code after the configSections node...

    Now retrieve the values like this:
    Dim strConnect As String = System.Configuration.ConfigurationManager.AppSettings("live")

    connectionStrings:
    <connectionStrings> <add name="connect" connectionString="Data Source=myServer;User Id=myUserID;Password=myPass;Initial Catalog=NORTHWIND" providerName="System.Data.SqlClient" />

    </connectionStrings>

     This code will then retrieve the connection string:

    Dim strConnect As String = System.Configuration.ConfigurationManager.AppSettings("connect")

    As always, your comments are welcome