25

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.

Community
  • 1
  • 1
Mass Dot Net
  • 2,150
  • 9
  • 38
  • 50

4 Answers4

35

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.

João Angelo
  • 56,552
  • 12
  • 145
  • 147
  • I think this is what I need, but I'm unable to access the variables via C#. When I type "Settings." Intellisense doesn't see anything... – Mass Dot Net Nov 20 '09 at 18:35
  • 2
    It's not really baked into the framework, it's rather an IDE thing. When you add a `.settings` file to your C#/VB project, it's used to generate code for class `Settings` that wraps config settings as properties of the appropriate type, and does all the necessary casts etc. – Pavel Minaev Nov 20 '09 at 20:59
  • 3
    This is a good answer...however it does not externalize the settings for users to change. If you change a value in a .settings file, then you must rebuild your solution to get the new value! Users tend to get pissy about things like that. :) – SASS_Shooter Dec 09 '14 at 21:48
  • 1
    FYI, the first part of "Settings.Default..." refers to the name of your .settings file. Mine was named AppSettings.settings, so I had to use "AppSettings.Default..." – Justas Mar 18 '16 at 02:44
  • If you're getting "An error occurred while reading the app.config file." when trying to `serializeAs` anything besides a string, first, do `serializeAs="String"`, switch to the project settings, then you can go back and change String to whatever type you want to use. – Josh Noe Aug 03 '16 at 15:25
28
Boolean isWeekend = Convert.ToBoolean(ConfigurationManager.AppSettings["IsWeekend"])
abatishchev
  • 98,240
  • 88
  • 296
  • 433
JayG
  • 612
  • 1
  • 6
  • 11
  • 11
    Or Boolean.TryParse(...). http://msdn.microsoft.com/en-us/library/system.boolean.tryparse.aspx – Mike Atlas Nov 20 '09 at 17:54
  • 8
    doesn't this fail the "strongly-typed variables" portion of the requirements, you're still storing a string in app.config – Nathan Koop Nov 20 '09 at 18:13
  • Yeah, I don't want to have to recast a string as the proper type. – Mass Dot Net Nov 20 '09 at 18:24
  • 1
    I was gong to add to my answer that this really isn't strongly typed for anything other than strings, but the phone rang. You would only need to use convert on non string data types. Still though, I upvoted João Angelo's answer, it looks like it might be a little slicker. – JayG Nov 20 '09 at 19:40
  • Or var isWeekend = Boolean.Parse(ConfigurationManager.AppSettings["IsWeekend"] ?? "false") – Christo Apr 23 '14 at 13:17
  • I would instead make a class that has some annotations on it that describe the config key name and the type and let that be how you do the mapping. Then just make a class that has all the strong type variables that match the settings section in the config file. – user441521 Aug 24 '16 at 14:58
2

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.

tobsen
  • 5,328
  • 3
  • 34
  • 51
0

Sounds like you want to have a custom <configSection>. Basically, it works like this:

-Create a configuration class that has proper default values, etc, and set up a nice inheritance structure so it'll auto-load based on your web.config settings. -Add your config section to the web.config, specifying the "type" that will load your settings so the .NET framework will know what to initialize

You can find all kinds of info on the MSDN library about it. The examples are asp.net, but they work just fine with app configs as well.

Graham Clark
  • 12,886
  • 8
  • 50
  • 82
Jerod Venema
  • 44,124
  • 5
  • 66
  • 109