问题
I wish to know what the best way is to create Saving and Loading logic so that I can save and load x items. For example, in Isolated Storage I can easily save a composite/POCO object by doing this:
var settings = IsolatedStorageSettings.ApplicationSettings;
settings.Add("key", myObject);
And load like this:
var settings = IsolatedStorageSettings.ApplicationSettings;
return settings["key"] as MyObject;
But how would I load x amount of Objects from IsolatedStorage? Would it be best to create a List<MyObject>
collection and save and whenever I want to save another object I basically load the existing and do .Add(newObject)
and save again?
So something like this:
List<MyObject> myObjects = new List<MyObject>();
myObjects.Add(newObject);
settings.Add("myObjects", myObjects);
and when Loading:
var myObjects = settings["myObjects"] as List<MyObject>;
This would however require deleting and adding the collection back in as settings.Add
requires a unique key. Would this be the best way?
I'd much rather use settings than a Iso File.
回答1:
Due to MSDN : IsolatedStorageSettings provide a convenient way to store user specific data as key-value pairs in a local IsolatedStorageFile. A typical use is to save settings, such as the number of images to display per page, page layout options, and so on.
so I don't think that using IsolatedStorageSettings would be your best option , if I were you , I would use IsolatedStorageFile.
To save and load the content of your list , the scenario would be
1- if an item is added or removed from your list , you searlize the list to xml and save it IsolatedStorageFile
private static void Serialize(string fileName, object source)
{
var userStore = IsolatedStorageFile.GetUserStoreForApplication();
using (var stream = new IsolatedStorageFileStream(fileName, FileMode.Create, userStore))
{
XmlSerializer serializer = new XmlSerializer(source.GetType());
serializer.Serialize(stream, source);
}
}
2- When you want to load your list at any place , you would deserialize the xml file stored in IsolatedStorageFile
public static void Deserialize<T>(ObservableCollection<T> list , string filename)
{
list = new ObservableCollection<T>();
var userStore = IsolatedStorageFile.GetUserStoreForApplication();
if (userStore.FileExists(filename))
{
using (var stream = new IsolatedStorageFileStream(filename, FileMode.Open, userStore))
{
XmlSerializer serializer = new XmlSerializer(list.GetType());
var items = (ObservableCollection<T>)serializer.Deserialize(stream);
foreach (T item in items)
{
list.Add(item);
}
}
}
}
来源:https://stackoverflow.com/questions/18197696/isolated-storage-saving-multiple-objects