If you just want to access the appSettings section of the configuration file, you can inherit it from the DynamicObject class and override the TryGetMember method:
public class DynamicSettings : DynamicObject { public DynamicSettings(NameValueCollection settings) { items = settings; } private readonly NameValueCollection items; public override bool TryGetMember(GetMemberBinder binder, out object result) { result = items.Get(binder.Name); return result != null; } }
Then, if this is your app.config file:
<configuration> <appSettings> <add key="FavoriteNumber" value="3" /> </appSettings> </configuration>
... the setting "FavoriteNumber" can be obtained as follows:
class Program { static void Main(string[] args) { dynamic settings = new DynamicSettings(ConfigurationManager.AppSettings); Console.WriteLine("The value of 'FavoriteNumber' is: " + settings.FavoriteNumber); } }
Note that attempting to access the undefined key RuntimeBinderException . You can prevent this by changing the overridden TryGetMember to always return true , in which case the undefined properties will simply return null .
Justin rusbatch
source share