2010-06-10 52 views
1

我有2个项目共享一些appSettinsg和配置节。假设:我可以在一个普通的app.config文件中共享一些配置部分吗? .net

  • ProjectA拥有自己的app.config,其中包含其独特的settings/config部分。
  • 项目B同上...

现在每个app.config中我想指向包含一些常见的appSettings和配置部分第三共享.config文件,双方项目A和B.

使用

我知道我可以使用configSource属性来引用每个configSection的外部文件,但是从实验来看,这种方法只能为每个外部文件保存一个配置节(通过将configsection定义为其根元素) 。为了方便起见,我希望“常用”文件保存多个文件。

这可能吗?

回答

1

您可以将所有设置分组到您自己的自定义配置部分。那么当然,您可以使用上面提到的configSource属性将它们一起移动到不同的文件中。

对于AppSettings,您的自定义配置部分可以使用Add函数将其自己的值合并到正常的AppSettings(它是NameValueCollection)。这样你就不需要改变你的客户代码。

作为一个方面,这里是我的一些基类,我用它来为我的大多数自定义元素添加“externalConfigSource”属性,以允许我的一些子元素进一步分割文件(尽管这可能是你正在尝试的避免):

public class BaseConfigurationElement : ConfigurationElement 
{ 
    protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey) 
    { 
     var fileSource = reader.GetAttribute("externalConfigSource"); 
     if (!String.IsNullOrEmpty(fileSource)) 
     { 
      var file = new FileInfo(Path.Combine(AppDomainExtensions.ConfigurationFilePath(), fileSource)); 
      if (file.Exists) 
      { 
       using (var fileReader = file.OpenRead()) 
       { 
        var settings = new XmlReaderSettings(){ CloseInput = true, IgnoreProcessingInstructions = true, IgnoreWhitespace = true, IgnoreComments = true}; 
        using (var fileXmlReader = XmlReader.Create(fileReader, settings)) 
        { 
         var atStart = fileXmlReader.IsStartElement(); 
         base.DeserializeElement(fileXmlReader, serializeCollectionKey); 
        } 
       } 
       reader.Skip(); 
      } 
      else 
      { 
       throw new ConfigurationErrorsException("The file specified in the externalConfigSource attribute cannot be found", reader); 
      } 
     } 
     else 
     { 
      base.DeserializeElement(reader, serializeCollectionKey); 
     } 
    } 

    protected override bool OnDeserializeUnrecognizedAttribute(string name, string value) 
    { 
     if (name == "externalConfigSource") 
     { 
      return true; // Indicate that we do know it... 
     } 
     return base.OnDeserializeUnrecognizedAttribute(name, value); 
    } 
} 

public static class AppDomainExtensions 
{ 
    public static string ConfigurationFilePath() 
    { 
     return ConfigurationFilePath(AppDomain.CurrentDomain); 
    } 

    // http://stackoverflow.com/questions/793657/how-to-find-path-of-active-app-config-file 
    public static string ConfigurationFilePath(this AppDomain appDomain) 
    { 
     return Path.GetDirectoryName(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); 
    } 
} 
+0

刚看到上面很多路段的评论已自定义配置的部分,如果是的话,你可以扩展这个“externalConfigSource”代码的工作,但你必须给读者移动到合适的位置在文件中定位元素的开始。 – Reddog 2010-06-10 17:14:55

相关问题