using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System;
public sealed class Serializer
{
private Serializer() { }
public static string SerializeObject(object obj)
{
IFormatter formatter = new BinaryFormatter();
string result = string.Empty;
using (MemoryStream stream = new MemoryStream())
{
formatter.Serialize(stream, obj);
byte[] byt = new byte[stream.Length];
byt = stream.ToArray();
//result = Encoding.UTF8.GetString(byt, 0, byt.Length);
result = Convert.ToBase64String(byt);
stream.Flush();
}
return result;
}
public static object DeserializeObject(string str)
{
IFormatter formatter = new BinaryFormatter();
//byte[] byt = Encoding.UTF8.GetBytes(str);
byte[] byt = Convert.FromBase64String(str);
object obj = null;
using (Stream stream = new MemoryStream(byt, 0, byt.Length))
{
obj = formatter.Deserialize(stream);
}
return obj;
}
}再次单元测试通过了,说明修改有效,回头debug到“result = Convert.ToBase64String(byt); ”,result的值开头没有"\0"了,都是字母,这才证明了序列化成功的原因。之后对基于64位的字符串转换应该多加关注,往往能起到令人惊喜的效果,本案总算是结案了。
浙公网安备 33010602011771号