How to save variable values on program exit?

前端 未结 4 1402
攒了一身酷
攒了一身酷 2020-12-31 23:57

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

相关标签:
4条回答
  • 2021-01-01 00:12

    Have a look at isolated storage.

    0 讨论(0)
  • 2021-01-01 00:15

    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<String> (List<String> 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.

    0 讨论(0)
  • 2021-01-01 00:20

    You can save the ArrayList (if not ArrayList their are other equivalent classes) using Properties.Settings best part is it allows you the setting variable at 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

    0 讨论(0)
  • 2021-01-01 00:39

    I've always done using (In Winforms in your case from the sounds of it), the Form_Closing to store to a Properties.Settings variable you'd create beforehand. If it's an ArrayList, you could store it to XML or a comma separated list. Your serizliation/deserialization method will depend on your data.

    0 讨论(0)
提交回复
热议问题