}
///
/// 将XML数据反序列化为指定类型对象
///
///
///
///
private static T DeserializeWithXml
{
MemoryStream stream = new MemoryStream();
stream.Write(data, 0, data.Length);
//注意,在反序列化的时候,将byte[]写入流以后,需要将游标移到首位,即将Position置零,否则反序列化将报错
stream.Position = 0;
XmlSerializer xs = new XmlSerializer(typeof(T));
object obj = xs.Deserialize(stream);
stream.Close();
return (T)obj;
}
///
/// 将json的二进制文件转换为string
///
///
///
private static String ByteToJsonString(byte[] json)
{
return Encoding.Default.GetString(json, 0, json.Length);
}
///
/// 将 Stream 写入文件
///
private static void StreamToFile(Stream stream, string filepath)
{
// 把 Stream 转换成 byte[]
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
// 设置当前流的位置为流的开始
stream.Seek(0, SeekOrigin.Begin);
// 把 byte[] 写入文件
FileStream fs = new FileStream(filepath, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(bytes);
bw.Close();
fs.Close();
}
}
///
/// 将对象序列化为XML数据
///
///
///
private static byte[] SerializeToXmlBytes(object obj)
{
MemoryStream stream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(obj.GetType());
xs.Serialize(stream, obj);
byte[] data = stream.ToArray();
stream.Close();
return data;
}