Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using App.config to set strongly-typed variables

Tags:

I'm a C# novice running .NET 3.5, and I'd like to store a bunch of application default values in App.config, as the settings may vary by server environment (e.g. development, staging, production). What I want to do is similar to what's described in this StackOverflow article, but I also want to be able to use non-string values (e.g. int, bool). Something like this (name-values are just examples, btw):

<?xml version="1.0" encoding="utf-8" ?> <configuration>     <applicationSettings>         <MyApp>             <setting name="InitText" serializeAs="String">                 <value>Hello</value>             </setting>             <setting name="StartAt" serializeAs="Integer">                 <value>5</value>             </setting>             <setting name="IsWeekend" serializeAs="Boolean">                 <value>True</value>             </setting>         </MyApp>     </applicationSettings> </configuration> 

Could somebody provide an example of how to do this, and how to retrieve the values via C#? I've seen a lot of examples that require using and , but I'm not sure if I need those elements, and if so, how to create them.

like image 931
Mass Dot Net Avatar asked Nov 20 '09 17:11

Mass Dot Net


2 Answers

What about using the Application Settings architecture of the .NET Framework. You can have strongly typed access to the default values.

On a Windows Application project the Settings file is created automatically in the Resources folder. You can then add application settings that are persisted in the App.config file just as you showed in your question.

For example:

int i = Settings.Default.IntSetting;  bool b = Settings.Default.BoolSetting; 

Edit: If your project does not contain the settings file you can always add one by adding a New Item and then choosing a Settings File. (Right click project file and do: Add->New Item->Settings File). In my case I named it Settings but you can name it whatever you want.

After adding the file visual studio will open the settings designer in which you can add your strongly-typed settings. From what you said you should set the settings at the Application scope and not at the user. Then build the project and you should get access to a class with the name of the file.

like image 140
João Angelo Avatar answered Sep 30 '22 06:09

João Angelo


Boolean isWeekend = Convert.ToBoolean(ConfigurationManager.AppSettings["IsWeekend"]) 
like image 38
JayG Avatar answered Sep 30 '22 04:09

JayG