只需使用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