C#中的二进制序列化

我正在尝试使用C#中的二进制序列化序列化类对象。我已经尝试了,到处都可以找到序列化数据,在我所看到的所有示例中,总是将序列化数据保存到文件中。

就我而言,我必须将序列化的数据存储在SQL中。以下是我创建的方法的示例。

//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();
}

如何直接在字符串变量中获取序列化数据?我不想使用文件。

请帮助。

aniu8258 回答:C#中的二进制序列化

只需使用MemoryStream ms = new MemoryStream()而不是文件流。 您可以通过调用ms.ToArray()来在串行化后为存储到SQL提取byte []。

不要忘记将您的Stream放入using声明中,以确保正确分配分配的资源。

,

C#中将字节数组表示为字符串的最简单方法是使用base64编码。下面的示例显示了如何在代码中实现此目标。

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

这将创建字符串encodedObject。要从字符串中检索字节数组和序列化的对象,请使用以下代码。

            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);
本文链接:https://www.f2er.com/3035961.html

大家都在问