反序列化字节数组
如果我想从二进制文件填充结构,我会使用这样的东西:
using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open)))
{
myStruct.ID = br.ReadSingle();
myStruct.name = br.ReadBytes(20);
}
但是,我必须在反序列化之前将整个文件读入字节数组,因为我想做一些预处理。是否有任何托管方式从字节数组填充我的结构,最好类似于上面的方式?
If I wanted to fill a structure from a binary file, I would use something like this:
using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open)))
{
myStruct.ID = br.ReadSingle();
myStruct.name = br.ReadBytes(20);
}
However, I must read the whole file into a byte array before deserializing, because I want to do some pre-processing. Is there any managed way to fill my structure from the byte array, preferably similar to the one above?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个示例,用于获取一些数据(实际上是 System.Data.DataSet)并序列化为字节数组,同时使用 DeflateStream 进行压缩。
这是反序列化的反向代码:
希望这会有所帮助。正如 Nate 所暗示的,我们在这里使用 MemoryStream。
This is a sample to take some data (actually a System.Data.DataSet) and serialize to an array of bytes, while compressing using DeflateStream.
Here is the code in reverse to deserialize:
Hope this helps. As Nate implied, we are using MemoryStream here.
查看 BitConverter 类。这可能会满足您的需要。
Take a look at the BitConverter class. That might do what you need.
对于不可序列化且仅包含基类型的非常简单的结构,这是有效的。我用它来解析具有已知格式的文件。为了清楚起见,删除了错误检查。
结构需要像这样声明(并且不能包含数组,我认为,还没有尝试过 - 字节序交换可能会感到困惑)。
For very simple structs which aren't Serializable and contain only base types, this works. I use it for parsing files which have a known format. Error checking removed for clarity.
Structs need to be declared like this (and can't contain arrays, I think, haven't tried that out - the endian swap would probably get confused).