Getting the path of web.config in a ConfigurationSection
I was writing my own ConfigurationSection class, and wanted to be able to both define settings inline (in web.config, in this case) or in a separate file. Also, I wanted to reference the external file without specifying a full path in the config file. Mainfully because full paths make transferring configs to production machines harder because the base path is (most likely) different on the development machine that on the production machine. And so I wanted to do:
But also:
(config params here)
Turns out there’s no easy way to get the path of the source file when in a ConfigurationSection class. The docs mention the ElementInformation property, which has a Source property. That property should be set to the source filename of the configuration section. Except: it doesn’t. Of course, I could resort to using HttpContext and Server.MapPath(“/web.config”) or something alike, but that adds a dependency to System.Web where it’s not really necessary (although the code will surely run in an ASP.Net environment, so I could use this approach). Also, I want to be able to use multiple web.config files in separate directories, and that would require me to build logic to search the directory hierarchy for the correct file. That only complicates matters, and it’s probably highly inefficient too. Through Reflector I found out that the XmlReader you get when overriding the DeserializeSection() method on your ConfigurationSection also implements the IConfigErrorInfo interface. That interface has 2 methods defined:
namespace System.Configuration.Internal {
public interface IConfigErrorInfo {
string Filename { get; }
int LineNumber { get; }
}
}
Hah, that interface has a Filename info. And it’s set too, when deserializing the section content. Nice.
And so you can just say:
IConfigErrorInfo info = reader as IConfigErrorInfo;
if (info != null && !string.IsNullOrEmpty(info.Filename)) {
realsrc = Path.Combine(Path.GetDirectoryName(info.Filename), src);
}
I guess that’s not the intented use for that class, but at least it works.