如何获取特定类型的所有部分

How to get all sections of a specific type

假设我的配置中有以下内容:

<configSections>
  <section name="interestingThings" type="Test.InterestingThingsSection, Test" />
  <section name="moreInterestingThings" type="Test.InterestingThingsSection, Test" />
</configSections>

<interestingThings>
  <add name="Thing1" value="Seuss" />
</interestingThings>

<moreInterestingThings>
  <add name="Thing2" value="Seuss" />
</moreInterestingThings>

如果我想获取任何一个部分,我可以很容易地通过名称获取它们:

InterestingThingsSection interesting = (InterestingThingsSection)ConfigurationManager.GetSection("interestingThings");
InterestingThingsSection more = (InterestingThingsSection)ConfigurationManager.GetSection("moreInterestingThings");

但是,这取决于我的代码知道该部分在配置中的命名方式 - 它可以命名为任何名称。我更喜欢的是能够从配置中提取类型为 InterestingThingsSection 的所有部分,而不考虑名称。我怎样才能以灵活的方式解决这个问题(因此,同时支持应用程序配置和网络配置)?

编辑: 如果您已经有了 Configuration,获取实际部分并不难:

public static IEnumerable<T> SectionsOfType<T>(this Configuration configuration)
    where T : ConfigurationSection
{
    return configuration.Sections.OfType<T>().Union(
        configuration.SectionGroups.SectionsOfType<T>());
}

public static IEnumerable<T> SectionsOfType<T>(this ConfigurationSectionGroupCollection collection)
    where T : ConfigurationSection
{
    var sections = new List<T>();
    foreach (ConfigurationSectionGroup group in collection)
    {
        sections.AddRange(group.Sections.OfType<T>());
        sections.AddRange(group.SectionGroups.SectionsOfType<T>());
    }
    return sections;
}

但是,如何以普遍适用的方式获取 Configuration 实例?或者,我怎么知道我应该使用 ConfigurationManager 还是 WebConfigurationManager

这可能不是最好的方法,但您可以正常阅读配置文件 xml,然后解析您想要的部分。例如,如果它是一个网络应用程序:

XmlDocument myConfig= new XmlDocument();
myConfig.Load(Server.MapPath("~/Web.config"));
XmlNode xnodes = myConfig.SelectSingleNode("/configSections");

现在您可以在 运行 时看到您关心的发现名称的节点,然后访问您的配置文件的特定节点。

另一个解决方案是:

Path.GetFileName(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)

如果这个returns"web.config",它可能是一个网络应用程序。

不过,HostingEnvironment.IsHosted是为了表明appdomain是否配置为ASP.NET下的运行,所以不能确定你的是web应用。

尝试使用ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)方法。它将当前应用程序的配置文件作为 Configuration 对象打开。

MSDN 文档:https://msdn.microsoft.com/en-us/library/ms134265%28v=vs.110%29.aspx

到目前为止,这似乎是最好的方法:

var config = HostingEnvironment.IsHosted
    ? WebConfigurationManager.OpenWebConfiguration(null) // Web app.
    : ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // Desktop app.