C#对象二进制序列化 [英] C# Object Binary Serialization

查看:256
本文介绍了C#对象二进制序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打一个对象的二进制序列化,并将结果保存在数据库中。

I want to make a binary serialize of an object and the result to save it in a database.

Person person = new Person();
person.Name = "something";

MemoryStream memorystream = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(memorystream, person);

我怎么能在一个字符串类型转换的MemoryStream要保存在数据库中,并在此之后才能够反序列化对象?

How can I transform memorystream in a string type to be saved in database, and after this to be able to deserialize the object?

推荐答案

你是什么的真正的要求的是重新presenting任意的二进制数据作为文本的一种安全的方式,然后将其转换再次回来。它存储序列化对象的事实是无关紧要的。

What you're really asking for is a safe way of representing arbitrary binary data as text and then converting it back again. The fact that it stores a serialized object is irrelevant.

答案几乎使用基地64(如 Convert.ToBase64String 和<一个href=\"http://msdn.microsoft.com/en-us/library/system.convert.frombase64string.aspx\"><$c$c>Convert.FromBase64String).做的的使用 Encoding.UTF8.GetString 或任何类似 - 你的二进制数据的的EN codeD文字数据,而不应被视为这样

The answer is almost to use Base 64 (e.g. Convert.ToBase64String and Convert.FromBase64String). Do not use Encoding.UTF8.GetString or anything similar - your binary data is not encoded text data, and shouldn't be treated as such.

不过,您的数据库没有为二进制数据的数据类型?检查BLOB,图像和二进制类型...

However, does your database not have a data type for binary data? Check for BLOB, IMAGE and BINARY types...

这篇关于C#对象二进制序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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