问题
I am trying to develop Windows 8 apps using C# and I need to store two list's (string and DateTime) in local settings
List<string> names = new List<string>();
List<DateTime> dates = new List<DateTime>();
I used LocalSettings for that according to this page: http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh700361
Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
But I have problems while I am storing Lists and getting back them from saved settings.
Can you help by sending couple of lines to store and retrieve string List and DateTime list type objects (or some other method to store this kind of data).
Thanks.
回答1:
Here is one libarary called Windows 8 Isolated storage, it uses XML serialization. You can store object
as well as List<T>
. The usage is also so much easy. Just add DLL in your project ans you have methods for storing the data.
public class Account
{
public string Name { get; set; }
public string Surname{ get; set; }
public int Age { get; set; }
}
Save in Isolated Storage:
Account obj = new Account{ Name = "Mario ", Surname = "Rossi", Age = 36 };
var storage = new Setting<Account>();
storage.SaveAsync("data", obj);
Load from Isolated Storage:
public async void LoadData()
{
var storage = new Setting<Account>();
Account obj = await storage.LoadAsync("data");
}
Also If you want to store List : Save a List in Isolated Storage:
List<Account> accountList = new List<Account>();
accountList.Add(new Account(){ Name = "Mario", Surname = "Rossi", Age = 36 });
accountList.Add(new Account(){ Name = "Marco", Surname = "Casagrande", Age = 24});
accountList.Add(new Account(){ Name = "Andrea", Surname = "Bianchi", Age = 43 });
var storage = new Setting<List<Account>>();
storage.SaveAsync("data", accountList );
Load a List from Isolated Storage:
public async void LoadData()
{
var storage = new Setting<List<Account>>();
List<Account> accountList = await storage.LoadAsync("data");
}
回答2:
Please check this sample, it demonstrates how to save a collection to application storage: http://code.msdn.microsoft.com/windowsapps/CSWinStoreAppSaveCollection-bed5d6e6
回答3:
try this to store:
localSettings.Values["names"] = names
localSettings.Values["dates"] = dates
and this to read:
dates = (List<DateTime>) localSettings.Values["dates"];
edit: it looks like I was wrong, and that you can only store basic types this way. So you may have to serialize everything into, say, a byte[] by using a MemoryStream and saving just its buffer.
来源:https://stackoverflow.com/questions/16070308/windows-8-app-local-storage