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;
using
System.Web.UI.Design;
//...

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:

config.AppSettings.Settings["maxRetries"].Value

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值