BrynnyBob BrynnyBob - 11 days ago 7
C# Question

Best way to retain variable values in the event of power off?

Is there a way to initialize a value to a memory address other than a specific value? I have a winform that opens at startup and I'd like it to save the user's previous entries. My (crappy) idea is to embed a text file and read the value from that file into the concerned variables? Is there a more professional / cleaner way of doing what I want?

To be clear, say I have a variable:

string pet = "dog"
. Later in the program the user will change this value to say
"fish"
. Now I want to store that value somewhere, and retain it in the event of a power off event so that when the program relaunches, the variable
pet
will be initialized to the stored memory value,
"fish"
.

Answer

A good way of achieving what you want is to use 'Settings'

Once configured, you can set them at user or application level in your code like so:

Properties.Settings.Default.Pet = "dog";
Properties.Settings.Default.Save();

https://msdn.microsoft.com/en-us/library/aa730869(v=vs.80).aspx