Thursday, 15 March 2012

c# - How to extract and resolve values within linked config file -



c# - How to extract and resolve values within linked config file -

i have file called log.config referenced in appsettings part of app.config.

within log.config have line (see below line fits log.config) ...

<file type="log4net.util.patternstring" value="${allusersprofile}/dir1/log/log.txt" />

i want retrieve total pathname of log.txt. i.e. extract value , resolve variable. i.e. string:

c:\programdata\dir1\log\log.txt

is possible? (i have tried fiddling system.configuration.configurationmanager cant figure out how it.)

log.config...

<?xml version="1.0" encoding="utf-8" ?> <configuration> <configsections> <section name="log4net" type="log4net.config.log4netconfigurationsectionhandler, log4net" /> </configsections> <log4net> <appender name="hourlyappender" type="log4net.appender.rollingfileappender"> <file type="log4net.util.patternstring" value="${allusersprofile}/dir1/log/log.txt" /> <appendtofile value="false" /> . . . . .

the way log4net resolve variables using optionconverter.substitutevariables, , in case of environment variables uses environment.getenvironmentvariables() dictionary of of them.

so use:

log4net.util.optionconverter.substitutevariables("${allusersprofile}/dir1/log/log.txt", environment.getenvironmentvariables())

and result c:\programdata/dir1/log/log.txt.

another alternative resolve environment variable using regex capture , environment.expandenvironmentvariables expand it:

regex.replace("${allusersprofile}/dir1/log/log.txt", @"\$\{(.*)\}", m => environment.expandenvironmentvariables(string.format("%{0}%", m.groups[1])))

to read part of config file, create appropriate iconfigurationsectionhandler.

log4net provide 1 (log4netconfigurationsectionhandler), it's not useful here. since configuration xml, can create utilize of selectsinglenode method:

xmlelement config = (xmlelement)configurationmanager.getsection("log4net"); string path = config.selectsinglenode("appender/file").attributes["value"].value;

c#

No comments:

Post a Comment