序列化一个对象在C#中,并得到字节流字节、对象、序列化

2023-09-03 01:32:54 作者:囚鸟

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

我知道我可以使用 的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的
{
    公共字符串名称;
}
 

IO流相关知识 File,字节流,字符流,特殊操作流 标准输入流,标准输出流,对象序列化与反序列化,properties与IO流结合 相关知识总结

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;
}