Thứ Năm, 2 tháng 10, 2008

Getting Configuration Parameters from app.config

How to get a configuration parameter from app.config
Visual Basic 2005 (vb.net)

Visual Basic automatically makes an app.config file in the root folder of your application. This is true for C# too. This file contains all sorts of configuration parameters that VB uses, as well as any custom ones that you care to define.
One very useful parameter is the Connection String that is used to connect to a SQL Server or MS Access database. This parameter is simply called ConnectionString.
If you want to read any of these configuration parameters from the app.config file at runtime, you need to do the following:

1. Add a reference to System.Configuration to the reference section of your project. (Look for it in Solution Explorer.)

2. Insert the statement:
imports system.configuration
at the top of your VB code file.

3. Then to access the parameter, use this:
Dim connectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings( "myConnectionString").ConnectionString

Your app.config file is just some XML,...........

As another tip, if you have multiple configuration strings, sometimes referring to them by name can be a pain, so you can refer to them by number instead, using 0 as the first one, 1 as the second, etc:
System.Configuration.ConfigurationManager.ConnectionStrings( 0).ConnectionString

Không có nhận xét nào: