给出一些对象列表:
List<Car> carlist = new List<Car>();
如何将此列表序列化为XML或二进制文件并将其反序列化?
到目前为止,我有这个,但它不起作用.
//IsolatedStorageFile isFile = IsolatedStorageFile.GetUserStoreForApplication();
//IsolatedStorageFileStream ifs = new IsolatedStorageFileStream("myxml.xml",FileMode.Create,isFile);
//DataContractSerializer ser = new DataContractSerializer();
//XmlWriter writer = XmlWriter.Create(ifs);
//ser.WriteObject(writer,carlist);
我正在使用这些方法从/到IsolatedStorage的XML文件中保存和加载:
public static class IsolatedStorageOperations
{
public static async Task Save<T>(this T obj,string file)
{
await Task.Run(() =>
{
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream stream = null;
try
{
stream = storage.CreateFile(file);
XmlSerializer serializer = new XmlSerializer(typeof (T));
serializer.Serialize(stream,obj);
}
catch (Exception)
{
}
finally
{
if (stream != null)
{
stream.Close();
stream.dispose();
}
}
});
}
public static async Task<T> Load<T>(string file)
{
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
T obj = Activator.CreateInstance<T>();
if (storage.FileExists(file))
{
IsolatedStorageFileStream stream = null;
try
{
stream = storage.OpenFile(file,FileMode.Open);
XmlSerializer serializer = new XmlSerializer(typeof (T));
obj = (T) serializer.Deserialize(stream);
}
catch (Exception)
{
}
finally
{
if (stream != null)
{
stream.Close();
stream.dispose();
}
}
return obj;
}
await obj.Save(file);
return obj;
}
}
您可以在catch()中自定义错误处理.
此外,您可以根据需要调整Load方法,在我的情况下,我尝试从文件加载,如果不存在,则创建默认值并根据构造函数放置提供的类型的默认序列化对象.
更新:
假设你有这样的汽车列表:
列表与LT;汽车> carlist = new List< Car>();
要保存,您可以将它们称为await carlist.Save(“myXML.xml”);,因为它是异步任务(异步).
要加载,var MyCars = await IsolatedStorageOperations.Load<列表与LT;车> >( “myXML.xml”). (我想,到目前为止,我没有像这样使用它作为列表...