c# - 在 C# 中读取自定义配置部分的键值

标签 c# configuration-files

我需要从 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]);
}

结果:

enter image description here

关于c# - 在 C# 中读取自定义配置部分的键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16524594/

相关文章:

glassfish - 如何指定默认的 glassfish-web.xml?

c# - 聪明的算法找到数字总和等于数字显示中的段数的时间

c# - 调试 ASP.NET 无法使用前导 .. 退出顶级目录

c# - 将小数插入 sql 会导致插入零数而不是接近零的十进制数

asp.net-mvc-4 - 在MVC的App_Start()文件夹中使用AuthConfig,BundleConfig,FilterConfig,RouteConfig和WebApiConfig

javascript - 新 web 项目上 javascript 配置的最佳实践

asp.net - 什么是 appSettings 键有效字符?

c# - InitializeComponent() 无法根据系统语言定位资源

c# - 为Elasticsearch日期字段提供空值

configuration - Hadoop 配置属性返回 Null