我有一个List< class>数据的.我想保存它并在每次我的应用程序启动和退出时检索它.什么是Windows 8中的IsolatedStorage(WP7).如何保存这些设置?
在Windows 8中,您必须为您的应用程序使用LocalFolder,您可以使用以下方法访问:
StorageFolder folder = ApplicationData.Current.LocalFolder;
然后使用以下参考文件保存在那里:
var fileToGet = await folder.GetFileAsync("nameOfFile.fileType");
我目前处于我正在处理的项目中的类似情况,我希望将自定义对象列表存储到我的Apps LocalFolder并稍后重新加载.
我的解决方案是将列表序列化为XML字符串,并将其存储在App文件夹中.你应该能够调整我的方法:
static public string SerializeListToXml(List<CustomObject> List) { try { XmlSerializer xmlIzer = new XmlSerializer(typeof(List<CustomObject>)); var writer = new StringWriter(); xmlIzer.Serialize(writer,List); System.Diagnostics.Debug.WriteLine(writer.ToString()); return writer.ToString(); } catch (Exception exc) { System.Diagnostics.Debug.WriteLine(exc); return String.Empty; }
现在您已经拥有了该字符串,您可以将其保存为文本文件并将其放在LocalStorage中:
//assuming you already have a list with data called myList await Windows.Storage.FileIO.WriteTextAsync("xmlFile.txt",SerializeListToXml(myList));
现在,当您再次加载应用程序时,您可以使用上面提到的加载方法从LocalStorage获取xmlFile,然后对其进行反序列化以使List返回.
string listAsXml = await Windows.Storage.FileIO.ReadTextAsync(xmlFile.txt); List<CustomObject> deserializedList = DeserializeXmlToList(listAsXml);
再次,根据您的需求进行调整:
public static List<CustomObject> DeserializeXmlToList(string listAsXml) { try { XmlSerializer xmlIzer = new XmlSerializer(typeof(List<CustomObject>)); XmlReader xmlRead = XmlReader.Create(listAsXml); List<CustomObject> myList = new List<CustomObject>(); myList = (xmlIzer.Deserialize(xmlRead)) as List<CustomObject>; return myList; } catch (Exception exc) { System.Diagnostics.Debug.WriteLine(exc); List<CustomObject> emptyList = new List<CustomObject>(); return emptyList; } }