Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persisting the data in app.config between debugging sessions

So, long story short, I'm developing an application that will make use of some configuration info that may be changed at runtime through the application itself. For the purpose I've thought of using the Settings class.

The problem, thought, is that information is not persisted between different runs of the application:

Run 1)

Console.WriteLine(Settings.Default["User"]); //prints "Default user"
Settings.Default["User"] = "abc";
Console.WriteLine(Settings.Default["User"]); //prints "abc"

Run 2)

Console.WriteLine(Settings.Default["User"]); //prints "Default user"
Settings.Default["User"] = "abc";
Console.WriteLine(Settings.Default["User"]); //prints "abc"

(both print exactly the same output)

Both runs show up the same first print "Default user", although on the 2nd run I'd like to get "abc", indicating that the info is not being persisted between different application executions.

I acknowledge this must be related with the way Visual Studio handles .config files, but even so I'd like to know how to correct for this (nasty) behavior?

like image 829
devoured elysium Avatar asked Mar 23 '13 03:03

devoured elysium


1 Answers

By default, App.config is not copied directly, rather it's content is placed in <assembly-name>.config file in output folder. Copy settings do not apply to this operation.

Generally, it is not a good practice for application to change its own app.config. If you are developing application that may be used by several users on the same PC, then use Settings instead. That way each user can have his own settings.

For services and system-wide settings, consider using another storage, like a separate config file, registry or database.

Edit about saving Settings:

When using settings class, you should call Save() to write it to the file, otherwise changes in settings will be discarded when application is closed. If you often terminate your application during development, and it does not reach it's end code(where you would normally place a call to Save()), then you have several options:

  1. Use debugger watch window to call Save(). To do that, place an expression like Settings.Default.Save() in watch window and refresh it every time you want to save.
  2. You can try using a timer to call Save every second.
  3. You can insert Save() calls in your code after settings change.
  4. You can write custom Settings provider or wrapper that will immediately save settings after every change.
like image 95
alex Avatar answered Sep 21 '22 18:09

alex