C# 阅读自定义配置部分';C中的s键值#

C# 阅读自定义配置部分';C中的s键值#,c#,configuration-files,C#,Configuration Files,我需要从app/web.config中的自定义部分读取键值 我通过了 及 但是,当我们需要显式指定配置文件的路径时(在我的情况下,配置文件不在其默认位置),它们不会指定如何读取自定义节 my web.config文件的示例: <?xml version="1.0" encoding="utf-8" ?> <configuration> <MyCustomTag> <add key="key1" value="value1" />

我需要从app/web.config中的自定义部分读取键值

我通过了

但是,当我们需要显式指定配置文件的路径时(在我的情况下,配置文件不在其默认位置),它们不会指定如何读取自定义节

my 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>

我在[keyName]

部分收到一个错误,指出“无法访问受保护的内部索引器'this'here”,不幸的是,这并不像听起来那么容易。解决此问题的方法是使用
ConfigurationManager
获取文件config file,然后使用原始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]);
}
var bla=GetNameValueCollectionSection(“MyCustomTag”,@.\XMLFile1.xml”);
for(int i=0;i
结果是:


Formo让它变得非常简单,比如:

dynamic config = new Configuration("customSection");
var appBuildDate = config.ApplicationBuildDate<DateTime>();
dynamic config=新配置(“customSection”);
var appBuildDate=config.ApplicationBuildDate();

请参见,添加您的web.config(完整或部分)。与web.config中自定义设置的路径无关。您将使用
@FrancescoDeLisi问题编辑。@saravanan在这种情况下customConfig是什么?@user85030:它是一个包含所有
的文件。这个答案没有提到为什么这种方法比定义自定义节类更好(对于简单的情况,它更直接,但仍然)。@Kai谢谢。我接受了你的回答@“\XMLFile1.xml”是配置文件的路径,对吗?@Kai它可以工作!此外,为了提高性能,我用字典取代了NameValueCollection。
dynamic config = new Configuration("customSection");
var appBuildDate = config.ApplicationBuildDate<DateTime>();