How to save the values โ€‹โ€‹of variables when exiting the program?

I am trying to use an ArrayList to store a variable number of lines and would like to know how to save an ArrayList and its elements so that my window shape can remember their meaning between loading and exiting the program.

I used to store information in a text file, but would like to avoid external files if possible.

Thanks for any help you could provide.

+4
source share
4 answers

You can save an ArrayList (if not ArrayList - these are other equivalent classes) using Properties.Settings , this is the best part, it allows you to set the configuration variable at the application and user level

A very good example can be found here how to use Settigns http://www.codeproject.com/Articles/17659/How-To-Use-the-Settings-Class-in-C

+6
source

I always used (in Winforms in your case from its sounds) Form_Closing to save the Properties.Settings variable that you would create in advance. If it is an ArrayList, you can save it in XML or in a comma-separated list. Your serizliation / deserialization method will depend on your data.

+2
source

Take a look at isolated storage .

+1
source

I used to store information in a text file, but would like to avoid external files if possible.

Inevitably storing data between runs, requires something outside of the executable programs.

The registry will work, but the registry is not very good for storing anything more than a small amount of information. A database can be used to add files.

For text lines, a text file โ€” one line in line 1 โ€” can be saved and loaded into a single statement. Placing a file in isolated storage or in a dedicated folder in% AppData% limits the user's chances of ruining it. 2 .

// Load var theStrings = new ArrayList(); var path = GetSavePath(); if (File.Exists(path)) { theStrings.AddRange(File.ReadLines(path); } // Save: File.WriteAllLines(GetSavePath(), theStrings.ToArray()); 

Here, using ToArray() as an ArrayList does not implement IEnumerable<String> ( List<String> would be the best choice for the collection and avoid this).


1 This assumes that the end of the line is not valid inside the lines. If necessary for support, there are a number of options. Some file format for separating lines with another mechanism, or perhaps the easiest, will be to avoid characters with a simple conversion (for example. \ โ†’ \\ , newline โ†’ \n , and carriage return โ†’ \r ).

2 You cannot prevent this without significant additional complexity, which will use something like a service to load / save as another user, which allows you to protect ACL data.

+1
source

All Articles