I am trying to load a custom section using the standard XmlSerializer from the current app/webapp's config file.
The below solution doesn't work for web apps:
var configFilePath =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
.FilePath;
if (configFilePath == null || !File.Exists(configFilePath))
return null;
var xdoc = XDocument.Load(configFilePath);
var section =
xdoc.Root?.Element("ParentSection")?.Element("MySection");
if (section == null)
return null;
var serializer = new XmlSerializer(typeof(MyConfigType));
MyConfigType config;
using (var reader = new StringReader(section.ToString()))
{
config = serializer.Deserialize(reader) as MyConfigType;
}
How can this be done easily without check if the current app is a web app or not?
(Without using System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration
?)
The config file path can be resolved like so:
var configFilePath =
AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
Answer based on Sean's deleted answer https://stackoverflow.com/a/27038942/38368 to a different question