本文实例讲述了.net的序列化与反序列化的实现方法。分享给大家供大家参考。具体方法如下:
1.序列化与反序列化概述
C#中如果需要:将一个结构很复杂的类的对象存储起来,或者通过网路传输到远程的客户端程序中去,这时就需要用到序列化,反序列化(Serialization & Deserialization)
2.BinaryFormattter
.NET中串行有三种,BinaryFormatter, SoapFormatter和XmlSerializer.
其中BinaryFormattter最简单,它是直接用二进制方式把对象 (Object)进行串行或反串,他的优点是速度快,可以串行private或者protected的member, 在不同版本的。NET中都兼容,可以看作是。NET自己的本命方法,当然缺点也就随之而来了,离开了。NET它就活不了,所以不能在其他平台或跨网路上进 行。
3.序列化
MemoryStream ms = new MemoryStream();
ser.Serialize(ms, DS);
byte[] buffer = ms.ToArray();</div>
MemoryStream :创建其支持存储区为内存的流
4.反序列化
MemoryStream ms = new MemoryStream(bytes);
BinaryFormatter ser = new BinaryFormatter();
DataSetSurrogate dss = ser.Deserialize(ms) asDataSetSurrogate;</div>
5.完整实例:
using System.Collections.Generic;
using System.Text;
using System.IO.Compression;
using System.IO;
namespace Common
{
/// <summary>
/// 利用GzipStream进行压缩和解压
/// </summary>
public class GZipUtil
{
private static GZipStream gZipStream = null;
/// <summary>
/// 压缩
/// </summary>
/// <param name="srcBytes"></param>
/// <returns></returns>
public static byte[] Compress(byte[] srcBytes)
{
MemoryStream ms = new MemoryStream(srcBytes);
gZipStream = new GZipStream(ms, CompressionMode.Compress);
gZipStream.Write(srcBytes, 0, srcBytes.Length);
gZipStream.Close();
return ms.ToArray();
}
/// <summary>
/// 解压
/// </summary>
/// <param name="srcBytes"></param>
/// <returns></returns>
public static byte[] Decompress(byte[] srcBytes)
{
MemoryStream srcMs = new MemoryStream(srcBytes);
gZipStream = new GZipStream(srcMs, CompressionMode.Decompress);
MemoryStream ms = new MemoryStream();
byte[] buffer = new byte[40960];
int n;
while ((n = gZipStream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, n);
}
gZipStream.Close();
return ms.ToArray();
}
/// <summary>
/// 将指定的字节数组压缩,并写入到目标文件
/// </summary>
/// <param name="srcBuffer">指定的源字节数组</param>
/// <param name="destFile">指定的目标文件</param>
public static void CompressData(byte[] srcBuffer, string destFile)
{
FileStream destStream = null;
GZipStream compressedStream = null;
try
{
//打开文件流
destStream = new FileStream(destFile, FileMode.OpenOrCreate, FileAccess.Write);
//指定压缩的目的流(这里是文件流)
compressedStream = new GZipStream(destStream, CompressionMode.Compress, true);
//往目的流中写数据,而流将数据写到指定的文件
compressedStream.Write(srcBuffer, 0, srcBuffer.Length);
}
catch (Exception ex)
{
throw new Exception(String.Format("压缩数据写入文件{0}时发生错误", destFile), ex);
}
finally
{
&