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

695 Views Asked by At

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".

3

There are 3 best solutions below

2
On BEST 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

0
On

Object Serialization is what you're looking for. See Here for more info.

There are a few ways to do it depending on your needs. Writing to/reading from a text file is a solution amongst others.

0
On

A common way to do this is to store it in the registry. Here is a tutorial that although a bit old, will help you with the general idea:

All you wanted to know about the registry with C#

Nothing wrong with using a text file either. Just keep in mind the security aspect of things. Wherever you store it, you will need to make sure you have write access. Some apps use configuration files that live in the root folder of the application for this reason. User context should also be considered when using the registry.