在webservice中将dataset序列化是我们经常遇到的问题,但是遇到很大的dataset,则网络传输就必须考虑的问题,将dataset处理压缩后传输是我们不错的选择,下面提供这种方法:
第一步:引入命名空间下载DataSetSurrogate组件
using System.IO.Compression;
using System.Runtime.Serialization.Formatters.Binary;
将下载好的DataSetSurrogate放入bin路径下
第二步:压缩序列化
///序列化转化为二进制数组的DataSet
public byte[] GetDataSetSurrogateZipBYtes(DataSet DS)
{
DataSetSurrogate dss = new DataSetSurrogate(DS);
///二进制方式方式序列化
BinaryFormatter ser = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
ser.Serialize(ms, dss);
byte[] buffer = ms.ToArray();
///调用压缩方法
byte[] Zipbuffer = Compress(buffer);
return Zipbuffer;
}
///压缩二进制文件
private byte[] Compress(byte[] data)
{
MemoryStream ms = new MemoryStream();
Stream zipStream = null;
zipStream = new GZipStream(ms, CompressionMode.Compress, true);
///从指定的字节数组中将压缩的字节写入基础流
zipStream.Write(data, 0, data.Length);
zipStream.Close();
ms.Position = 0;
byte[] Compressed_Data = new byte[ms.Length];
ms.Read(Compressed_Data, 0, int.Parse(ms.Length.ToString()));
return Compressed_Data;
}
第三部:解压反序列化
///将压缩后的二进制数组解压
public static byte[] Decompress(byte[] data)
{ ///data参数为压缩后的二进制数组
try
{
MemoryStream ms = new MemoryStream(data);
Stream zipStream = null;
zipStream = new GZipStream(ms, CompressionMode.Decompress);
byte[] dc_data = null;
dc_data = EtractBytesFormStream(zipStream, data.Length);
return dc_data;
///返回解压后的二进制数组
}
catch
{
return null;
}
}
/// 将二进制文件反序列化后转化为DataSet
public DataSet GetDatasetFromByte(byte[] ZipByte)
{
byte[] buffer = UnZipClass.Decompress(ZipByte);
BinaryFormatter ser = new BinaryFormatter();
DataSetSurrogate dss;
dss = (DataSetSurrogate)ser.Deserialize(new MemoryStream(buffer));
DataSet DS = dss.ConvertToDataSet();
return DS;
}
至此完成操作,欢迎指导。