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

VB.NET

Notes, Tricks and Tips on VB.NET

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

 

Comments

 

Varun Sharma said:

hi

I added system.configuration reference using

Import System.Configuration.

but when i tried to implement the above mentioned code i am getting this error:

Error 1 ' ConfigurationManager' is not a member of 'Configuration'.

July 10, 2007 3:27 AM
 

Steve Gray said:

I found this posted somewhere else, but I haven't tried it. If you get it working let me know what fixed it and I'll update this post

===================================

The easiest way to do this is to import System.WebConfiguration and

use:

Dim s As String =

WebConfigurationManager.ConnectionStrings("foo").C onnectionString

July 10, 2007 9:16 AM
 

Antonio said:

I had the same problem, but it's just a matter of add the reference of System.Configuration using the Add references menu.

July 25, 2008 4:25 PM

Leave a Comment

(required)  
(optional)
(required)  
Add

About Steve Gray

Steve is a seasoned (translate: old) developer in VB and ASP.NET. He spends most of his time in Dynamics GP, writing custom mods for consulting firms. Crystal reports, eConnect, VS Tools for Dynamics... anything that comes along.