【问题标题】:Load configuration file from stream instead of file从流而不是文件加载配置文件
【发布时间】:2011-05-04 00:35:12
【问题描述】:

我使用 OpenMappedExeConfiguration 和 ExeConfigurationFileMap 来加载配置文件。它们的重载表明它们仅适用于文件名。有没有办法从流中加载配置文件?

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

【问题讨论】:

    标签: .net configuration web-config app-config


    【解决方案1】:

    没有。问题是这个类本身不读取配置。文件路径本身最终会被Configuration类用来加载配置,而这个类其实想要一个物理路径。

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

    【讨论】:

    • msdn.microsoft.com/en-us/library/… 的摘录说明了对“物理”路径的需求:“配置类实例表示来自适用于特定物理实体的所有配置文件的配置设置的合并视图”
    【解决方案2】:

    是的。 如果您的应用程序被允许更改应用程序文件夹中的文件 - 更新 *.config 文件,通过文件 IO 操作或执行“update/save/@987654324 部分@”。此解决方案中有直接的逻辑 - 想要进行远程配置?从远程获取它,更新本地并拥有它。

    示例:假设您已将 wcf 部分的组(<bindings><behaviors>.. 等)存储在文件 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 验证子系统很重要。如果更新顺序错误,可能会出现验证异常。

    【讨论】:

      猜你喜欢
      • 2016-06-09
      • 1970-01-01
      • 2018-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-30
      • 1970-01-01
      相关资源
      最近更新 更多