C# 对象二进制序列化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1749044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:28:21  来源:igfitidea点击:

C# Object Binary Serialization

c#stringserializationbinaryformatter

提问by Emanuel

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

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

如何将内存流转换为字符串类型以保存在数据库中,然后才能反序列化对象?

采纳答案by Jon Skeet

What you're reallyasking 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.

真正需要的是一种将任意二进制数据表示为文本然后再次将其转换回来的安全方式。它存储序列化对象的事实无关紧要。

The answer is almost to use Base 64 (e.g. Convert.ToBase64Stringand Convert.FromBase64String). Do notuse Encoding.UTF8.GetStringor anything similar - your binary data is notencoded text data, and shouldn't be treated as such.

答案几乎是使用 Base 64(例如Convert.ToBase64StringConvert.FromBase64String)。千万不能使用Encoding.UTF8.GetString或任何类似-您的二进制数据编码的文本数据,并且不应该被如此对待。

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

但是,您的数据库没有二进制数据的数据类型吗?检查 BLOB、IMAGE 和 BINARY 类型...

回答by Adriaan Stander

I used something like this

我用过这样的东西

MemoryStream memoryStream = new MemoryStream();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, Person);
memoryStream.Flush();
memoryStream.Position = 0;
string value = Convert.ToBase64String(memoryStream.ToArray());

回答by Jan Jongboom

Basically, don'tsave the data as string to the database, there are blobfields available to store binary data.

基本上,不要将数据作为字符串保存到数据库中,有一些blob字段可用于存储二进制数据。

If you really need to have the data as string, you'll need to convert your byte[] to a string using base64 encoding, and to grab the byte[] from a string use decoding.

如果您确实需要将数据作为字符串,则需要使用 base64 编码将 byte[] 转换为字符串,并使用解码从字符串中获取 byte[]。

回答by t0mm13b

Have you not looked into converting the memorystream into a base64hex string to be put into the database?

您是否没有考虑将内存流转换为 base64hex 字符串以放入数据库?

 byte[] mStream = memorystream.ToArray();
 string sConvertdHex = System.Convert.ToBase64String(mStream)

Then you can dump the contents sConvertdHex to the database. To deserialize it you need to do the reverse

然后您可以将内容 sConvertdHex 转储到数据库。要反序列化它,你需要做相反的事情

 byte[] mData = System.Convert.FromBase64String(...)

then deserialize mData back to your object.

然后将 mData 反序列化回您的对象。

回答by Siarhei Kuchuk

Here's the sample. TData must be marked [Serializable] and all fields type also.

这是示例。TData 必须标记为 [Serializable] 并且所有字段类型也是。

    private static TData DeserializeFromString<TData>(string settings)
    {
        byte[] b = Convert.FromBase64String(settings);
        using (var stream = new MemoryStream(b))
        {
            var formatter = new BinaryFormatter();
            stream.Seek(0, SeekOrigin.Begin);
            return (TData)formatter.Deserialize(stream);
        }
    }

    private static string SerializeToString<TData>(TData settings)
    {
        using (var stream = new MemoryStream())
        {
            var formatter = new BinaryFormatter();
            formatter.Serialize(stream, settings);
            stream.Flush();
            stream.Position = 0;
            return Convert.ToBase64String(stream.ToArray());
        }
    }

回答by Ramakrishna Talla

//-------write to database-------------------------
Person person = new Person();
person.name = "Firstnm  Lastnm";
MemoryStream memorystream = new MemoryStream(); 
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(memorystream, person);
byte[] yourBytesToDb = memorystream.ToArray();
//here you write yourBytesToDb to database


//----------read from database---------------------
//here you read from database binary data into yourBytesFromDb
MemoryStream memorystreamd = new MemoryStream(yourBytesFromDb);
BinaryFormatter bfd = new BinaryFormatter();
Person deserializedperson = bfd.Deserialize(memorystreamd) as Person;