【发布时间】:2011-10-22 15:31:41
【问题描述】:
这对我来说似乎很简单,但我似乎无法找到正确的谷歌查询来帮助我..
我有 一些 web.config 文件位于 C:\temp 中,并且希望能够使用像 myWebConfig.AppSettings["myParam"] 这样的东西。
这个可以吗?
我尝试使用ConfigurationManager.OpenMappedMachineConfiguration、ConfigurationManager.OpenExeConfiguration、WebConfigurationManager.OpenWebConfiguration 和WebConfigurationManager.OpenMappedWebConfiguration。
也许我只是没有以正确的方式使用它们或者..?
[更新]
tvanfossen 写的是正确的。我没有编辑权限,所以我将在这里编写我最后使用的代码。
/* Method based on what I found on http://stackoverflow.com/questions/4339167/how-to-read-a-configuration-section-from-xml-in-a-database/4844365#4844365
* and tvanvossens answer.
* There's probably room for improvement, but it does what I need now.
*/
private static T GetSection<T>(string pathToWebConfigFile, string configNode) where T : ConfigurationSection, new()
{
var doc = XDocument.Load(pathToWebConfigFile);
var element = doc.Element("configuration").Element(configNode);
var reader = element.CreateReader();
var settingsSection = new T();
settingsSection.GetType().GetMethod("DeserializeSection", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(settingsSection, new object[] { reader });
return settingsSection;
}
用法示例:
var settingsSection = GetSection<AppSettingsSection>(pathToWebConfigFile, "appSettings");
var connectionStringSection = GetSection<ConnectionStringsSection>(pathToWebConfigFile, "connectionStrings");
【问题讨论】:
标签: .net web-config configurationmanager