序列化一个对象在C#中,并得到字节流 [英] Serialize an object in C# and get byte stream

查看:92
本文介绍了序列化一个对象在C#中,并得到字节流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象序列化类,实例。我想知道你怎么能得到这个对象作为字节流?

我知道我可以使用 的BinaryFormatter 然后使用序列化的方法,但这种方法需要一个 serializationStream 它写序列化对象。我希望能够在一个文件/流在特定位置写,所以我想这样做是这样的:

  OBJ =新的东西(); // obj是序列化
byte []的连载= obj.serialize(); [*]
file.write(位置,系列化)
 

有没有什么办法可以做到 [*] ,采取对象的序列化的字节?

解决方案

  MemoryStream的M =新的MemoryStream();
VAR格式化=新的BinaryFormatter();
formatter.Serialize(男,新MyClass的(){名称=SO});
byte []的BUF = m.ToArray(); //或File.WriteAllBytes(文件名,m.ToArray())


[可序列化]
公共类MyClass的
{
    公共字符串名称;
}
 

I have an object, instance of a Serializable class. I was wondering how can you get this object as a byte stream?

I know I can use BinaryFormatter and then use the Serialize method, but this method takes a serializationStream where it writes the serialized object. I want to be able to write it in a file/stream in a specific position so I would like to do something like:

obj = new Something(); // obj is serializable 
byte[] serialized = obj.serialize(); [*]
file.write(position, serialized)

Is there any way I can do the [*], to take the bytes of the serialization of an object?

解决方案

MemoryStream m = new MemoryStream();
var formatter = new BinaryFormatter();
formatter.Serialize(m, new MyClass() {Name="SO"});
byte[] buf = m.ToArray(); //or File.WriteAllBytes(filename, m.ToArray())


[Serializable]
public class MyClass
{
    public string Name;
}

这篇关于序列化一个对象在C#中,并得到字节流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆