WebConfigurationManager 和 ConfigurationManager 有什么区别?

WebConfigurationManagerConfigurationManager有什么区别?

我什么时候应该使用一个而不是另一个?

更新

我刚刚查看了 WebConfigurationManager,由于某种原因,您不能像在 ConfigurationManager中那样访问连接字符串(比如数组)。有人能告诉我为什么多发性硬化症会变成这样吗?使用 WebConfigurationManager获取所需的连接字符串似乎是一件痛苦的事情。

再次更新与警告!

如果没有对添加到项目中的 System.Configuration命名空间的引用,那么当您尝试像数组一样访问 WebConfigurationManager.ConnectionStrings时,VisualStudio 将显示一个错误!

37850 次浏览

WebConfigurationManager is made specifically for ASP.NET applications.

WebConfigurationManager provides additional methods to load configuration files applicable to Web applications.

ConfigurationManager provides also methods to load configuration files applicable to ".exe" applications.

I’d suggest taking a look at WebConfigurationManager and see if it provides you with anything you simply cannot do with ConfigurationManager and use it instead, otherwise using ConfigurationManager will make it far easier to have your code be used seamlessly between web and desktop aps.

WebConfigurationManger knows how to deal with configuration inheritance within a web application. As you know, there could be several web.config files in one applicaion - one in the root of the site and any number in subdirectories. You can pass path to the GetSection() method to get possible overridden config.

If we'd looke at WebConfigurationManager with Reflector then things are clear:

public static object GetSection(string sectionName)
{
...
return ConfigurationManager.GetSection(sectionName);
}


public static object GetSection(string sectionName, string path)
{
...
return HttpConfigurationSystem.GetSection(sectionName, path);
}

Not sure what you mean about the connection strings.

Calling WebConfigurationManager.ConnectionStrings returns a System.Configuration.ConnectionStringSettingsCollection, which is the same as you would get if you called ConfigurationManager.ConnectionStrings.

Otherwise, as XOR says, it's designed to handle multiple hierarchical web.configs, combining them as required as you move around the folders in an application.

Although WebConfigurationManager is located in the System.Web assembly the ConnectionStringSettingsCollection that it returns is located in System.Configuration.

If you are getting the error

Cannot apply indexing with [] to an expression of type 'System.Configuration.ConnectionStringSettingsCollection'

while trying to access the array index...

WebConfigurationManager.ConnectionStrings["Name"].ConnectionString

make sure you have a reference to assembly System.Configuration