首页 > 解决方案 > 使用库中的自定义方法从 C# 中的 App.config 获取所有对(键、值)

问题描述

我正在尝试构建自己的最常用方法/代码库。我目前正在使用的方法假设从配置文件中的用户提供的部分读取所有对(值,键)并将它们记录到记录器中。当我将代码转换为方法并将其移动到单独的文件时,我发现了与App.config位置相关的问题。

所以我有我的App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="General" type="System.Configuration.NameValueSectionHandler"/>
    <section name="Generalxxxxxxxxxxxxx" type="System.Configuration.NameValueSectionHandler"/>
  </configSections>
  <General>
    <add key="ApplicationName" value="Configuration Example Project"/>
    <add key="Language" value="CSharp"/>
    <add key="SecretKey" value="012345"/>
  </General>
  <Generalxxxxxxxxxxxxx>
    <add key="ApplicationName" value="Configuration Example Project"/>
    <add key="Language" value="CSharp"/>
    <add key="SecretKey" value="012345"/>
  </Generalxxxxxxxxxxxxx>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
</configuration>

只需使用以下代码,我就可以从中读取所有对(键,值)。在这种情况下,当所有内容都在一个文件下时,我不必提供App.config位置。

var general = ConfigurationManager.GetSection("General") as NameValueCollection;  
            if (applicationSettings.Count == 0)  
            {  
                Console.WriteLine("Application Settings are not defined");  
            }  
            else  
            {  
                foreach (var key in general.AllKeys)  
                {  
                    Console.WriteLine(key + " = " + applicationSettings[key]);  
                }  
            }  

我找到了一种传递位置的方法,但现在由于转换错误,我无法将sectionLoad读取为NameValueCollection,因此我无法使用AllKeys方法。

 public static Tuple<string, string> LogSaveConfig(string location, string sectionName)
        {

            //var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var config = ConfigurationManager.OpenExeConfiguration(location);

            var sectionLoad = config.GetSection(sectionName);

            return Tuple.Create("key", "value"); //just temporary
        }

我还对“sectionLoad”进行了一些调试,唯一能找到对(键、值)的地方是 rawXML: 在此处输入图像描述

我的问题是当我通过作为单独库的一部分的方法调用配置文件时如何获取对(键,值)?我的目标是能够键入MyLib.LoggerDefined.LogSaveConfig(location, section); 要将对(键,值)记录到记录器中的内容。另外,如果我的方法有误,请告诉我。谢谢。

标签: c#app-config

解决方案


您可以直接读取 xml 格式的 xml 文件。我使用了 xml linq 并创建了一个字典

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication158
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<string, List<List<KeyValuePair<string, string>>>> dict = doc.Root.Elements()
                .GroupBy(x => x.Name.LocalName, y => y.Elements()
                    .Select(z => z.Attributes().Select(a => new KeyValuePair<string, string>(a.Name.LocalName, (string)a)).ToList()).ToList())
                    .ToDictionary(x => x.Key, y => y.FirstOrDefault());

        }
    }
}

推荐阅读