Using App.config to set strongly-typed variables

63,214

Solution 1

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.

Solution 2

Boolean isWeekend = Convert.ToBoolean(ConfigurationManager.AppSettings["IsWeekend"])

Solution 3

The thing JayG suggested can be done by the Visual Studio automatically. Use the appsettings wizard as described in the MSDN. Also the whole Application Settings infrastructure might be worth a read.

Share:
63,214
Mass Dot Net
Author by

Mass Dot Net

Updated on July 15, 2020

Comments

  • Mass Dot Net
    Mass Dot Net almost 4 years

    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.