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?
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:
Settings.Default.Save()
in watch window and refresh it every time you want to save.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With