Load configuration file from stream instead of file

那年仲夏 提交于 2019-12-03 16:54:57

No. The problem is that this class itself do not read the configuration. The file path itself is eventually used by the Configuration class to load the configuration, and this class actually wants a physical path.

I think the only solution is to store the file to a temporary path and read it from there.

Yes. If your application is allowed to change files in the application folder - update *.config file, by file IO operations or by doing "section update/save/refresh" . There is straight forward logic in this solution - want to have remote configuration? Get it from remote, update local and have it.

Sample: let say you have stored your wcf section's group (<bindings>, <behaviors>.. etc) in the file wcfsections.test.config (of course any remote source is possible) and want to "overload" conf file configuration. Then configration update/save/refresh code looks like:

        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        ConfigurationSectionCollection sections = ServiceModelSectionGroup.GetSectionGroup(config).Sections;
        sections.Clear();

        string fileName = ((GeneralSettings)ConfigurationManager.GetSection("generalSettings")).AppConfigServiceModelSectionFile;

        XDocument doc = XDocument.Load(fileName);
        var xmlGroup = (from x in doc.Descendants("system.serviceModel") select x).FirstOrDefault();

        string[] sectionsInUpdateOrder = { "bindings", "comContracts", "behaviors", "extensions", "services", "serviceHostingEnvironment", "client", "diagnostics" };
        foreach (string key in sectionsInUpdateOrder)
        {
            var e = (from x in xmlGroup.Elements(key) select x).FirstOrDefault();
            if (e != null)
            {
                ConfigurationSection currentSection = sections[e.Name.LocalName];
                string xml = e.ToString();
                currentSection.SectionInformation.SetRawXml(xml);
            }
        }
        config.Save();
        foreach (string key in sectionsInUpdateOrder)
            ConfigurationManager.RefreshSection("system.serviceModel/" + key);

Note: the updates order is important for wcf validation subsystem. If you update it in wrong order, you can get validation exceptions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!