2010-11-02 77 views
5

我使用OpenMappedExeConfiguration和ExeConfigurationFileMap加载配置文件。它们的超载表明它们只能处理文件名。有没有办法从流中加载配置文件?从流而不是文件加载配置文件

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

回答

5

问题是这个类本身不读配置。文件路径本身最终被类加载配置使用,而这个类实际上需要一个物理路径。

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

+1

有时候“否”是正确答案:-) – 2010-11-08 09:54:00

+0

http://msdn.microsoft.com/en-us/library/system.configuration.configuration.aspx摘录说明需要一个“物理”路径:“Configuration类实例表示来自适用于特定物理实体的所有配置文件的配置设置的合并视图” – 2010-11-08 09:54:19

4

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

样品:让说你已经存储在您的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验证子系统很重要。如果您以错误的顺序更新它,则可能会得到验证异常。

相关问题