Learning While Aging

Retrieve web.config file through ASP.NET

How to get a hold of the web.config file in a web application?

ASP.NET has a WebConfigurationManager class that has a method called OpenMappedWebConfiguration. It can be used to open a web application configuration file as a configuration object. OpenMappedWebConfiguration has three overloads, and we can use the first one to open the web.config file:

WebConfigurationManager.OpenMappedWebConfiguration Method (WebConfigurationFileMap, String)

The first parameter is a WebConfigurationFileMap object, which specify the web file hierarchy. The second parameter is the virtual path to the configuration file.

So, first we need to create a WebConfigurationFileMap object:

Dim fileMap As New WebConfigurationFileMap()
Dim physDir As String = Server.MapPath(Request.ApplicationPath)
Dim vDirMap As New VirtualDirectoryMapping(physDir, True, "web.config")
fileMap.VirtualDirectories.Add("/", vDirMap)

Now, we can use OpenMappedWebConfiguration method to open the configuration file:

Dim config As System.Configuration.Configuration = WebConfigurationManager.OpenMappedWebConfiguration(fileMap, "/config")

With the config object, you can loop through it to get a specific value of a specific section. For example, the following line of code will display the first connection string value in web.config file:

Response.Write("Connection String: " & config.ConnectionStrings.ConnectionString(0))

Happy programming!