二进制序列化和反序列化而不创建文件(通过字符串)

我正在尝试创建一个类,该类将包含用于将对象序列化/反序列化到字符串/从字符串反序列化的函数。 这就是现在的样子:

public class BinarySerialization { public static string SerializeObject(object o) { string result = ""; if ((o.GetType().Attributes & TypeAttributes.Serializable) == TypeAttributes.Serializable) { BinaryFormatter f = new BinaryFormatter(); using (MemoryStream str = new MemoryStream()) { f.Serialize(str, o); str.Position = 0; StreamReader reader = new StreamReader(str); result = reader.ReadToEnd(); } } return result; } public static object DeserializeObject(string str) { object result = null; byte[] bytes = System.Text.Encoding.ASCII.GetBytes(str); using (MemoryStream stream = new MemoryStream(bytes)) { BinaryFormatter bf = new BinaryFormatter(); result = bf.Deserialize(stream); } return result; } } 

SerializeObject方法效果很好,但DeserializeObject却没有。 我总是得到一个exception消息“解析完成之前遇到的流结束”。 这可能有什么问题?

使用BinaryFormatter序列化对象的结果是八位字节流,而不是字符串。
您不能将字节视为C或Python中的字符。

使用Base64对序列化对象进行编码以获取字符串:

 public static string SerializeObject(object o) { if (!o.GetType().IsSerializable) { return null; } using (MemoryStream stream = new MemoryStream()) { new BinaryFormatter().Serialize(stream, o); return Convert.ToBase64String(stream.ToArray()); } } 

 public static object DeserializeObject(string str) { byte[] bytes = Convert.FromBase64String(str); using (MemoryStream stream = new MemoryStream(bytes)) { return new BinaryFormatter().Deserialize(stream); } } 

对编码和解码使用UTF8 Base64编码而不是ASCII。