2007-07-19

Application Configuration File


Sample Code to manage app.config

Dim strConfig As String
strConfig = System.Reflection.Assembly.GetExecutingAssembly().
CodeBase.Replace("file:///", "") + ".config"


Dim doc As XmlDocument = New System.Xml.XmlDocument()
doc.Load(strConfig)

' Get Node value
MessageBox.Show(doc.SelectSingleNode("descendant::
appSettings/add[@key='ConnectionString']").
Attributes("value").Value())


' Update Node value
doc.SelectSingleNode("descendant::appSettings/
add[@key='ConnectionString']").Attributes("value").Value
= "This is new connection string"

System.Configuration Basics

The System.Configuration namespace provides the functionality for reading configuration files. Microsoft released an XML schema dictating the format for configuration files that can be read using the System.Configuration API, enabling the accessing object to automatically consume the configuration files. This way, you can allow configuration files to be read without having to develop a bunch of plumbing to read the file and find the desired setting. Multiple types of configuration files are relevant to .NET, but this article focuses exclusively on the configuration files containing application-specific settings.

The name and storage location of an application configuration file depends on the application type with which it is being used. A configuration file for an executable (.exe) is located in the same directory as the application. The file is the name of the application with a .config extension. For example, notepad.exe would have a configuration file of notepad.exe.config. A configuration file for an ASP.NET application is called web.config and is located in the root of the application's virtual directory.

appSettings Section

An application configuration file follows a specific XML schema. The appSettings section is a predefined section of the configuration file designed to make it very easy to retrieve a value based on a given name. This is the easiest way to add application-specific settings into an application configuration file. The appSettings section of the configuration file consists of a series of "add" elements with "key" and "value" attributes. While the appSettings section is predefined, it is not included in a configuration file by default and must be manually added. A simple example of a configuration file would be the following:



read more



1 comment:

Anonymous said...

Thanks! Perfect!