How to store a list of objects in application settings

Application configuration is not the good choice for storing the data at application runtime. For this use any available in .NET serialization option like

  • Xml Serialization
  • Binary serialization with proto-buf
  • Json serialization
  • ORM mapping to some embedde database Sqlite

and many others...


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<tuple>):

void SaveTuples(List<tuple> 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<tuple> LoadTuples()
{
    using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(Properties.Settings.Default.tuples)))
    {
        BinaryFormatter bf = new BinaryFormatter();
        return (List<tuple>)bf.Deserialize(ms);
    }
}

Example:

List<tuple> list = new List<tuple>();
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.