开发者

Traverse .config file in exe or web app

I'm writing a library that will be used in desktop and web apps. It needs to traverse the section groups in the .config file. I assume I'll need an instan开发者_运维百科ce of System.Configuration.Configuration to do this. Is there a way to do this that works in desktop and web apps?


I ended up with something like this:

static Configuration OpenConfiguration() {
    if (HttpContext.Current != null)
        return WebConfigurationManager.OpenWebConfiguration(null);
    return ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}

static IEnumerable<ConfigurationSectionGroup> GetConfigSectionGroups() {
    var config = OpenConfiguration();
    var stack = new Stack<ConfigurationSectionGroup>();
    stack.Push(config.RootSectionGroup);
    while (stack.Count > 0) {
        var group = stack.Pop();
        yield return group;
        foreach (ConfigurationSectionGroup subGroup in group.SectionGroups) {
            stack.Push(subGroup);
        }
    }
}


I would use the WebConfigurationManager/ConfigurationManager to read specific configuration sections and return a ConfigurationSection object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜