Reputation: 1940
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
Reputation: 60556
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.
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();
}
}
You said in a comment that you try to save application settings. Consider using Application Settings.
Upvotes: 1
Reputation:
Easiest way is to just store them as user-scoped application settings
Then you can just access them via static properties
MyApplication.Properties.Settings.Default.StringOne = "herpaderp";
MyApplication.Properties.Settings.Default.Save();
Upvotes: 3
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