Dirk Brockhaus
Dirk Brockhaus

Reputation: 5062

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!

Upvotes: 6

Views: 4803

Answers (2)

Roman Pokrovskij
Roman Pokrovskij

Reputation: 9776

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.

Upvotes: 4

Pieter van Ginkel
Pieter van Ginkel

Reputation: 29642

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.

Upvotes: 7

Related Questions