数据序列化后保存成文件File.BIN,如果数据更新后,如何把数据进行序列化后,追加在原有序列化文件中,并且能读出数据。
问题补充:
序列化函数
/// <summary>
/// 数据追加序列化
/// </summary>
/// <typeparam name="T">追加的数据源</typeparam>
/// <param name="physicPath">原有序列化的文件File.Bin</param>
/// <param name="source"></param>
public static void SeekSerializable<T>(string physicPath, T source)
where T : class, new()
{
IFormatter format = new BinaryFormatter();
Stream stream = new FileStream(physicPath, FileMode.Append, FileAccess.Write, FileShare.None);
stream.Seek(0, SeekOrigin.End);
format.Serialize(stream, source);
stream.Close();
}
序列化函数
/// <summary>
/// 对象反序列化,必须是可序列化对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="physicPath"></param>
public static T Deserialize<T>(string physicPath)
{
IFormatter format = new BinaryFormatter();
Stream stream = new FileStream(physicPath, FileMode.Open, FileAccess.Read, FileShare.Read);
T entity = (T)format.Deserialize(stream);
stream.Close();
return entity;
}