Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load configuration file from stream instead of file

I use OpenMappedExeConfiguration with ExeConfigurationFileMap to load configuration files. Their overloads suggest that they only work with filenames. Is there a way to load a configuration file from a stream?

Background: I want to load configuration files that are stored as embedded resources. There is no file representation!

like image 916
Dirk Brockhaus Avatar asked Nov 02 '10 15:11

Dirk Brockhaus


2 Answers

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.

like image 198
Pieter van Ginkel Avatar answered Sep 22 '22 01:09

Pieter van Ginkel


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.

like image 23
Roman Pokrovskij Avatar answered Sep 18 '22 01:09

Roman Pokrovskij