Article Index

Accessing web.config at Design Time in .NET 2.0

When creating a designer for an ASP.NET server control, it is often very useful to read settings from the user's web.config file. In previous versions of the .NET Framework, you had to jump through hoops to access the web.config file at design time. I was very thankful for this solution when I needed it, but I'm happy to move on. The dependency on EnvDTE felt wrong, and the fact that it used COM interop with the VS.NET IDE meant it probably would not work with any other tool.

Thankfully, in .NET 2.0, it is much simpler. If you want to get the full path to web.config (useful for parsing the XML manually), it has been reduced to:

using System.Web.UI.Design;
IWebApplication webApp = (IWebApplication)Component.Site.GetService(
typeof(IWebApplication) );
IProjectItem item = webApp.GetProjectItemFromUrl("~/web.config");
string webConfigPath = item.PhysicalPath;

Note: you will want to check for nulls and handle appropriately. The call to GetService could return null if the design tool hosting your control does not support this service (something other than VS.NET). And of course the call to GetProjectItemFromUrl could fail if there is no web.config in the project.

Even better, instead of parsing web.config yourself, you can get strongly-typed access to the configuration using the new classes in the System.Configuration namespace. For example, in my ProfileView control, I use code similar (more null checking) to the following to discover information about the configured profile properties:

using System.Configuration;
using System.Web.Configuration;

IWebApplication webApp = (IWebApplication)Component.Site.GetService(
typeof(IWebApplication) );
Configuration config = webApp.OpenWebConfiguration(true);
ConfigurationSectionGroup systemWeb = config.GetSectionGroup("system.web");
ProfileSection profileSection = (ProfileSection)systemWeb.Sections["profile"];

foreach (ProfilePropertySettings configProperty in profileSection.PropertySettings)
{ // read the settings in each configProperty }

Once you get the Configuration object as demonstrated above, reading a value out of the appSettings section is as easy as:



Really thanks man for this article. ;)
Mahdi - February 19, 2008 01:33am