从流中加载配置文件而不是从文件加载

6

我使用ExeConfigurationFileMap中的OpenMappedExeConfiguration来加载配置文件。他们的重载表明它们只适用于文件名。有没有一种方法可以从流中加载配置文件?

背景:我想要加载作为嵌入式资源存储的配置文件。没有文件表示!

2个回答

7

问题:这个类本身不读取配置。文件路径最终由Configuration类用于加载配置,而这个类实际上需要一个物理路径。

解决方案:我认为唯一的解决方案是将文件存储到临时路径并从那里读取。


以下是有关编程的内容,需要将其从英语翻译成中文。请仅返回已翻译的文本:http://msdn.microsoft.com/en-us/library/system.configuration.configuration.aspx 的摘录说明了“物理”路径的必要性:“Configuration 类实例表示来自适用于特定物理实体的所有配置文件的配置设置的合并视图”。 - Dirk Brockhaus

4
是的。如果您的应用程序被允许更改应用程序文件夹中的文件-通过文件IO操作或执行“部分更新/保存/刷新”,则可以更新*.config文件。这种解决方案有一个简单的逻辑 - 想获得远程配置?从远程获取,更新本地并拥有它。
示例:假设您已将wcf部分的组(,等)存储在文件wcfsections.test.config中(当然存在任何远程源),并想要“重载”conf文件配置。然后,配置更新/保存/刷新代码如下:
        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);

注意:更新顺序对于WCF验证子系统非常重要。如果您按错误顺序进行更新,可能会出现验证异常。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接