use*_*694 6 c# configuration-files
我需要从app/web.config中的自定义部分读取键值.
我经历了
使用ConfigurationManager从Web.Config中读取密钥
和
但是,当我们需要显式指定配置文件的路径时,它们没有指定如何读取自定义部分(在我的情况下,配置文件不在其默认位置)
我的web.config文件示例:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<MyCustomTag>
<add key="key1" value="value1" />
<add key="key2" value="value2" />
</MyCustomTag>
<system.web>
<compilation related data />
</system.web>
</configuration>
Run Code Online (Sandbox Code Playgroud)
我需要在MyCustomTag中读取键值对.
当我尝试(configFilePath是我的配置文件的路径): -
var configFileMap = new ExeConfigurationFileMap { ExeConfigFilename = configFilePath };
var config =
ConfigurationManager.OpenMappedExeConfiguration(
configFileMap, ConfigurationUserLevel.None);
ConfigurationSection section = config.GetSection(sectionName);
return section[keyName].Value;
Run Code Online (Sandbox Code Playgroud)
我收到一条错误,指出"无法在[keyName]部分访问受保护的内部索引器'此'
不幸的是,这并不像听起来那么容易.解决问题的方法是获取文件配置文件,ConfigurationManager然后使用原始xml.所以,我通常使用以下方法:
private NameValueCollection GetNameValueCollectionSection(string section, string filePath)
{
string file = filePath;
System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
NameValueCollection nameValueColl = new NameValueCollection();
System.Configuration.ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = file;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
string xml = config.GetSection(section).SectionInformation.GetRawXml();
xDoc.LoadXml(xml);
System.Xml.XmlNode xList = xDoc.ChildNodes[0];
foreach (System.Xml.XmlNode xNodo in xList)
{
nameValueColl.Add(xNodo.Attributes[0].Value, xNodo.Attributes[1].Value);
}
return nameValueColl;
}
Run Code Online (Sandbox Code Playgroud)
并调用该方法:
var bla = GetNameValueCollectionSection("MyCustomTag", @".\XMLFile1.xml");
for (int i = 0; i < bla.Count; i++)
{
Console.WriteLine(bla[i] + " = " + bla.Keys[i]);
}
Run Code Online (Sandbox Code Playgroud)
结果:

| 归档时间: |
|
| 查看次数: |
16740 次 |
| 最近记录: |