我正在尝试将我的MMF序列化为文件,这是代码:
class MMF {
private const string filename = @"c:\NFS";
private long offset = 0;
private long length = 194;
private byte[] buffer;
public MMF() {
using (var mmf =
MemoryMappedFile.CreateFromFile(filename, FileMode.OpenOrCreate, null, offset + length, MemoryMappedFileAccess.ReadWriteExecute)) {
using (var accessor = mmf.CreateViewAccessor(offset, length, MemoryMappedFileAccess.ReadWriteExecute)) {
buffer = new byte[194];
/*FS fs = new FS();
fs.Files[0].Path = "test";
accessor.WriteArray<byte>(0, buffer, 0, (int)length);*/
accessor.ReadArray<byte>(0, buffer, 0, (int)length);
FS fs = (FS)ToObject(buffer);
Console.WriteLine(fs.Files[0].Path);
}
}
}
private byte[] ToByteArray(object source) {
var formatter = new BinaryFormatter();
using (var stream = new MemoryStream()) {
formatter.Serialize(stream, source);
return stream.ToArray();
}
}
private object ToObject(byte[] source) {
var formatter = new BinaryFormatter();
using (var stream = new MemoryStream(source)) {
formatter.Deserialize(stream);
return stream;
}
}
}
在反序列化部分,我收到错误:
未处理的类型异常 发生'System.Runtime.Serialization.SerializationException' mscorlib.dll中
附加信息:二进制流“0”不包含有效内容 二进制头BinaryHeader。可能的原因:无效的流或对象 序列化和反序列化之间的版本更改。
如何正确反序列化文件?我的错误在哪里?
谢谢