在C#中读取自定义配置部分的键值 [英] Reading custom configuration section's key values in C#
问题描述
我需要从app / web.config中的自定义部分读取键值。
I need to read key values from custom sections in app/web.config.
我经历了
使用ConfigurationManager从Web.Config读取密钥
和
How can I retrieve list of custom configuration sections in the .config file using C#?
但是,当我们需要显式指定配置文件的路径时,它们没有指定如何读取自定义节(在我的情况下,配置文件不在这是默认位置)
However, they do not specify how to read a custom section when we need to explicitly specify the path to the configuration file (in my case, the configuration file is not in it's default location)
我的web.config文件示例:
Example of my web.config file:
<?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内部的键值对。
in which i need to read key value pairs inside MyCustomTag.
当我尝试(configFilePath是我的配置文件的路径)时:-
When i try (configFilePath is the path to my configuration file):-
var configFileMap = new ExeConfigurationFileMap { ExeConfigFilename = configFilePath };
var config =
ConfigurationManager.OpenMappedExeConfiguration(
configFileMap, ConfigurationUserLevel.None);
ConfigurationSection section = config.GetSection(sectionName);
return section[keyName].Value;
我在[keyName]部分收到一条错误消息,指出无法在此处访问受保护的内部索引器'this'
I get a error stating "Cannot access protected internal indexer 'this' here" at section[keyName]
推荐答案
不幸的是,这并不像听起来那样简单。解决该问题的方法是使用 ConfigurationManager
获取文件配置文件,然后使用原始xml。因此,我通常使用以下方法:
Unfortunately, this is not as easy as it sounds. The way to solve the problem is to get file config file with ConfigurationManager
and then work with the raw xml. So, I normally use the following method:
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#中读取自定义配置部分的键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!