我有一个自定义类型列表,需要将它们保存到移动设备 (Windows Mobile 6) 上的文件或从文件加载它们,考虑到设备的有限资源,哪种方法最适合? 编辑: 数据文件将在 2-5mb 左右
请您参考如下方法:
我们在谈论多少数据?
我使用旧设备(HTC-s620,配备 TI OMAP 850 200 MHz 处理器)使用 XML 序列化在 3-5 秒内保存了一个 2mb 的 XML 文件。非常简单的编程模型。很容易做到。使用更新的设备,我相信它会更快。
我的使用场景是,每次运行一次完全加载,一次完全保存。
[XmlRoot("notes")]
public class NoteList : List<Note>
{
// Set this to 'default' or 'preserve'.
[XmlAttribute("space", Namespace = "http://www.w3.org/XML/1998/namespace")]
public string space = "preserve";
public static void Save(NoteList noteList, string NotesFilePath)
{
if (noteList == null) return;
XmlSerializer serializer = new XmlSerializer(typeof(NoteList));
string tmpPath = NotesFilePath + ".tmp";
using (System.IO.FileStream fs = new FileStream(tmpPath, FileMode.Create, FileAccess.Write))
{
serializer.Serialize(fs, noteList);
fs.Close();
}
if (File.Exists(tmpPath))
{
if (File.Exists(NotesFilePath))
{
string oldFile = NotesFilePath + ".bak";
if (File.Exists(oldFile)) File.Delete(oldFile);
File.Move(NotesFilePath, oldFile);
}
File.Move(tmpPath, NotesFilePath);
}
}
public static NoteList Load(string NotesFilePath)
{
if (!System.IO.File.Exists(NotesFilePath))
return null;
NoteList noteList = new NoteList();
XmlSerializer serializer = new XmlSerializer(noteList.GetType());
using (FileStream fs = new FileStream(NotesFilePath, FileMode.Open, FileAccess.Read))
{
noteList = (NoteList)serializer.Deserialize(fs);
fs.Close();
}
return noteList;
}
}
