[英]Binary Serialization in c#
I am trying to serialize a class object using binary serialization in C#. 我正在尝试使用C#中的二进制序列化序列化一个类对象。 I have tried and everywhere all I can find that the serialized data goes to a file always in all the examples I have seen. 我已经尝试过了,到处都可以找到序列化数据,在我所看到的所有示例中,该数据总是存储在文件中。
In my case, I have to store the serialized data in SQL. 就我而言,我必须将序列化的数据存储在SQL中。 The following is an example of the method I have created. 以下是我创建的方法的示例。
//Serializing the List
public void Serialize(Employees emps, String filename)
{
//Create the stream to add object into it.
System.IO.Stream ms = File.OpenWrite(filename);
//Format the object as Binary
BinaryFormatter formatter = new BinaryFormatter();
//It serialize the employee object
formatter.Serialize(ms, emps);
ms.Flush();
ms.Close();
ms.Dispose();
}
How can I get the serialized data directly in a string variable? 如何直接在字符串变量中获取序列化数据? I don't want to use a file. 我不想使用文件。
Please help. 请帮忙。
Just use MemoryStream ms = new MemoryStream()
instead of your file stream. 只需使用MemoryStream ms = new MemoryStream()
代替文件流即可。 You can extract a byte[] for Storage to SQL after serializing by calling ms.ToArray()
. 您可以在调用序列号为ms.ToArray()
序列化后提取byte []以便存储到SQL。
And don't forget to put your Stream into a using
-Statement, to guarantee correct disposal of the allocated resources. 并且不要忘记将您的Stream放入using
-Statement中,以确保正确分配分配的资源。
The easiest way to represent a byte array as a string in C#
is with base64
encoding. 在C#
中将字节数组表示为字符串的最简单方法是使用base64
编码。 The below example shows how this would be achieved within your code. 下面的示例显示了如何在代码中实现此目标。
public void Serialize(Employees emps, String filename)
{
//Create the stream to add object into it.
MemoryStream ms = new MemoryStream();
//Format the object as Binary
BinaryFormatter formatter = new BinaryFormatter();
//It serialize the employee object
formatter.Serialize(ms, emps);
// Your employees object serialised and converted to a string.
string encodedObject = Convert.ToBase64String(ms.ToArray());
ms.Close();
}
This creates the string encodedObject
. 这将创建字符串encodedObject
。 To retrieve the byte array and your serialised object back from the string you will use the below code. 要从字符串中检索字节数组和序列化的对象,您将使用以下代码。
BinaryFormatter bf = new BinaryFormatter();
// Decode the string back to a byte array
byte[] decodedObject = Convert.FromBase64String(encodedObject);
// Create a memory stream and pass in the decoded byte array as the parameter
MemoryStream memoryStream = new MemoryStream(decodedObject);
// Deserialise byte array back to employees object.
Employees employees = bf.Deserialize(memoryStream);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.