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);
}
請注意,上面顯示的代碼是不是最漂亮的,但它表明了意圖 - 我建議拆分出來爲若干獨立以及命名方法,每做一兩件事,把它做好=)