Reputation: 331
I've got a few properties stored in my AppConfig and now I want to access them dynamically (e.g. in a loop or function).
Accessing the values using MySettings.NAME_OF_THAT_THING is no problem, but what if the name is variable?
I tried:
String propertyValue = MySettings.GetType().GetProperty("NAME_OF_THAT_THING").ToString();
But the only thing I got back is the name of the property. How can I do this?
Upvotes: 10
Views: 10617
Reputation: 380
answer to the orginal poster question would be like: MySettings[NAME_OF_THAT_THINGmysettings] does the job like previous post
however for those people looking for answer to using the builtin settings in their windows app: myAppDefaultNameSpace.Properties.Settings.Default[NAME_OF_THAT_THINGmysettings] is the way to go
Upvotes: 0
Reputation: 43743
All you need to do is:
String propertyValue = Settings.Default["NAME_OF_THAT_THING"].ToString();
While using reflection will obviously work, it's overkill.
Upvotes: 12
Reputation: 8047
Have you tried using the ConfigurationManager.AppSettings property? You should be able to get your setting via the following code:
String propertyValue = ConfigurationManager.AppSettings["NAME_OF_THAT_THING"];
The MSDN article for ConfigurationManager.AppSettings also includes an example for looping through all of the entries in AppSettings by index, rather than name.
Upvotes: 0
Reputation: 60493
String propertyValue = MySettings.GetType()
.GetProperty("NAME_OF_THAT_THING")
.GetValue(MySettings, null); //replace MySettings with null in GetValue(...) if MySettings is a static class
Upvotes: 8