user629926
user629926

Reputation: 1940

How can I persist a list of object between application launches

I need to persist a list of object between application launches per user basis; how can I do it?

The object is simple: 4 strings and one int.

Upvotes: 2

Views: 1550

Answers (4)

dknaack
dknaack

Reputation: 60556

Description

One way is to use BinaryFormatter to save a list of serializable objects to a binary file. You can use the SoapFormatter if you want a readable / editable file.

Sample

Here a class that makes it possible to save a list of serializable objects.

[Serializable]
public class BinareObjectList<T> : List<T>
{
    public void LoadFromFile(string fileName)
    {
        if (!File.Exists(fileName))
            throw new FileNotFoundException("File not found", fileName);

        this.Clear();

        try
        {
            IFormatter formatter = new BinaryFormatter();
            // IFormatter formatter = new SoapFormatter();
            Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            List<T> list = (List<T>)formatter.Deserialize(stream);
            foreach (T o in list)
                this.Add(o);
            stream.Close();
        }
        catch { }
    }

    public void SaveToFile(string fileName)
    {
        if (File.Exists(fileName))
            File.Delete(fileName);

        IFormatter formatter = new BinaryFormatter();
        // IFormatter formatter = new SoapFormatter();
        Stream stream = new FileStream(fileName, FileMode.CreateNew);
        formatter.Serialize(stream, this);
        stream.Close();
    }
}

More Information:

Update

You said in a comment that you try to save application settings. Consider using Application Settings.

MSDN: Using Settings in C#

Upvotes: 1

user1228
user1228

Reputation:

Easiest way is to just store them as user-scoped application settings

enter image description here

Then you can just access them via static properties

MyApplication.Properties.Settings.Default.StringOne = "herpaderp";
MyApplication.Properties.Settings.Default.Save();

Upvotes: 3

user596075
user596075

Reputation:

I would vote for Isolated Storage.

Upvotes: 0

Oded
Oded

Reputation: 499352

Serialize the object to the users appdata directory or use the IsolatedStorage when you want to persist it and deserialize it when launching.

Upvotes: 4

Related Questions