2010-11-11 148 views
0

我正在尝试使用.Net配置模型来处理以类似的方式加载和合并一组配置文件的能力,这些配置文件类似于如何构建heirachical ASP.Net网络配置文件合并在一起。指定.Net配置文件的位置

感谢优秀的Unraveling the Mysteries of .NET 2.0 Configuration系列文章,我已经想出了如何做大部分事情,但是我在指定要加载的配置文件的确切流行时遇到了一些麻烦。就像使用web.config文件一样,可能会有无数的配置文件需要加载,并且需要在运行时确定应该包含哪些文件的规则。我正在谈论 - 如果用户正在处理文件“c:\ User \ jblogs \ Documents \ Projects \ MyApp \ AppFile12.txt”,那么我可能需要以下内容要被包括在所述heirachy文件:

  • C:\用户\ jblogs \文件\项目\ MyApp的\ myapp.config
  • C:\用户\ jblogs \文件\项目\ myapp.config
  • c:\ User \ jblogs \ myapp.config
  • c:\ Program Files \ MyApp \ config \ myapp.config

(免责声明:以上是我想要实现一个简单的例子,但我想,如果我能想出如何做上述那么我就已经破解吧)

我甚至尝试着在Reflector中查看web.config代码,但它很难理解到底发生了什么 - 任何懂得这一点的人都可以将我指向正确的方向吗?

回答

0
public class MyConfigObject 
{ 
    public class MyConfigObject(MyConfigObject parent) 
    { 
    // Copy constructor - don't alter the parent. 
    } 
} 

public class MyConfigHandler : IConfigurationSectionHandler 
{ 
    public object Create(object parent, object context, XmlNode section) 
    { 
    var config = new MyConfigObject((MyConfigObject)parent); 
    // Process section and mutate config as required 
    return config; 
    } 
} 

现在,当你需要申请配置的很多层面,简单地收集所有文件以层叠从目录中的文件是在工作的过程,然后通过出栈处理这些LIFO顺序。

var currentWorkingDirectory = Path.GetDirectoryName("c:\\User\\jblogs\\Documents\\Projects\\MyApp\\AppFile12.txt"); 
var currentDirectory = new DirectoryInfo(currentWorkingDirectory) 
var userDataRootDirectory = new DirectoryInfo("c:\\User\\jblogs\\"); 

var configFilesToProcess = new Stack<string>(); 

do 
{ 
    // Search for myapp.config in currentDirectory 
    // If found push path onto configFilesToProcess 
    currentDirectory = currentDirectory.GetParent(); 
} 
while(!currentDirectory.Equals(userDataRootDirectory) 

var applicationConfigPath = "c:\\Program Files\\MyApp\\config\\myapp.config"; 
configFilesToProcess.Push(applicationConfigPath); 

var configHandler = new MyConfigHandler(); 
object configuration = null; 
object configContext = null; // no idea what this is but i think it is the entire config file 
while(configFilesToProcess.Any()) 
{ 
    var configPath = configFilesToProcess.Pop(); 
    // Load config file 
    var configNode = null; // Extract your config node using xpath 
    configuration = configHandler.Create(configuration, configContext, configNode); 
} 

请注意,上面显示的代码是不是最漂亮的,但它表明了意图 - 我建议拆分出来为若干独立以及命名方法,每做一两件事,把它做好=)