您可以将所有设置分组到您自己的自定义配置部分。那么当然,您可以使用上面提到的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);
}
}
刚看到上面很多路段的评论已自定义配置的部分,如果是的话,你可以扩展这个“externalConfigSource”代码的工作,但你必须给读者移动到合适的位置在文件中定位元素的开始。 – Reddog 2010-06-10 17:14:55