I am trying to use an ArrayList to store a variable number of strings, and would like to know how to save the ArrayList and its elements so that my windows form can recall t
I used to store the information in a text file, but would like to avoid external files if possible.
Inevitably storing data between runs will require something outside the program's executables.
The registry would work, but the registry is not great for storing anything more than a small amount of information. A database could be used by that adds files.
For text strings a text file – one string per line1 – can be saved and loaded in a single statement. Putting the file into isolated storage or under a dedicated folder in %AppData% limits the chances of a user messing it up.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 ArrayList
doesn't implement IEnumerable
(List
would be a better choice for a collection and avoid this).
1 This assumes end of line is not valid inside the strings. If this needs to be supported there are a number of options. Some file format to separate the strings by another mechanism, or perhaps the easiest will be to escape characters with a simple transform (eg. \
→ \\
, newline → \n
, and carriage return → \r
).
2 You cannot prevent this without significant additional complexity that would use something like a service to load/save as a different user thus allowing the data to be protected by an ACL.