NameValueFileSectionHandler
This section handler allows <appSettings file="user.config" />
The file pointed to by the file= attribute is read as if it is
an appSettings section in the config file.
Note: the user.config file must have its root element match the
section referring to it. So if appSettings has a file="user.config"
attribute the root element in user.config must also be named appSettings.
using System.Configuration.Internal;
using System.IO;
using System.Xml;
namespace System.Configuration
{
public class NameValueFileSectionHandler : IConfigurationSectionHandler
{
public object Create(object parent, object configContext, XmlNode section)
{
XmlNode xmlNode = section.Attributes.RemoveNamedItem("file");
object obj = NameValueSectionHandler.CreateStatic(parent, section);
if (xmlNode != null && xmlNode.Value.Length != 0) {
string value = xmlNode.Value;
IConfigErrorInfo configErrorInfo = xmlNode as IConfigErrorInfo;
if (configErrorInfo == null)
return null;
string filename = configErrorInfo.Filename;
string directoryName = Path.GetDirectoryName(filename);
string text = Path.Combine(directoryName, value);
if (File.Exists(text)) {
ConfigXmlDocument configXmlDocument = new ConfigXmlDocument();
try {
configXmlDocument.Load(text);
} catch (XmlException ex) {
throw new ConfigurationErrorsException(ex.Message, ex, text, ex.LineNumber);
}
if (section.Name != configXmlDocument.DocumentElement.Name)
throw new ConfigurationErrorsException(System.SR.Format(System.SR.Config_name_value_file_section_file_invalid_root, section.Name), configXmlDocument.DocumentElement);
obj = NameValueSectionHandler.CreateStatic(obj, configXmlDocument.DocumentElement);
}
}
return obj;
}
}
}