我需要从 app/web.config 中的自定义部分读取键值。
我经历过
Reading a key from the Web.Config using ConfigurationManager
和
How can I retrieve list of custom configuration sections in the .config file using C#?
但是,当我们需要显式指定配置文件的路径时,它们没有指定如何读取自定义部分(在我的例子中,配置文件不在它的默认位置)
我的 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>
我需要在其中读取 MyCustomTag 中的键值对。
当我尝试时(configFilePath 是我的配置文件的路径):-
var configFileMap = new ExeConfigurationFileMap { ExeConfigFilename = configFilePath };
var config =
ConfigurationManager.OpenMappedExeConfiguration(
configFileMap, ConfigurationUserLevel.None);
ConfigurationSection section = config.GetSection(sectionName);
return section[keyName].Value;
我在 [keyName] 部分收到一条错误消息,指出“无法在此处访问 protected 内部索引器‘this’”
最佳答案
不幸的是,这并不像听起来那么容易。解决问题的方法是使用 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;
}
以及方法的调用:
var bla = GetNameValueCollectionSection("MyCustomTag", @".\XMLFile1.xml");
for (int i = 0; i < bla.Count; i++)
{
Console.WriteLine(bla[i] + " = " + bla.Keys[i]);
}
结果:
关于c# - 在 C# 中读取自定义配置部分的键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16524594/