How to store a list of objects in application settings

前端 未结 5 1218
时光取名叫无心
时光取名叫无心 2020-12-02 21:43

I have recently became familiar with C# application settings, and it seems cool.
I was searching for a way to store a list of custom objects, but I couldn\'t find a way!

5条回答
  •  旧时难觅i
    2020-12-02 21:48

    You can use BinaryFormatter to serialize list of tuples as byte array and Base64 (as quite efficient way) to store byte array as string.

    First of all change your class to something like that (hint: [SerializableAttribute]):

    [Serializable()]
    public class tuple
    {
        public tuple()
        {
            this.font = new Font("Microsoft Sans Serif", 8);
        //....
    }
    

    Add property in settings named tuples and type of string.

    tuples in Settings

    Then you can use two methods to load and save generic list of tuples (List):

    void SaveTuples(List tuples)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(ms, tuples);
            ms.Position = 0;
            byte[] buffer = new byte[(int)ms.Length];
            ms.Read(buffer, 0, buffer.Length);
            Properties.Settings.Default.tuples = Convert.ToBase64String(buffer);
            Properties.Settings.Default.Save();
        }
    }
    
    List LoadTuples()
    {
        using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(Properties.Settings.Default.tuples)))
        {
            BinaryFormatter bf = new BinaryFormatter();
            return (List)bf.Deserialize(ms);
        }
    }
    

    Example:

    List list = new List();
    list.Add(new tuple());
    list.Add(new tuple());
    list.Add(new tuple());
    list.Add(new tuple());
    list.Add(new tuple());
    
    // save list
    SaveTuples(list);
    
    // load list
    list = LoadTuples();
    

    I leave null, empty string and exception checking up to you.

提交回复
热议问题