场景


实现

在上面文章实现序列化和压缩的基础上,再进行解压缩和反序列化。

在form窗体上拖拽Button,双击进入其点击事件。

private void button10_Click(object sender, EventArgs e)
{
DateTime begin = DateTime.Now;
Console.WriteLine(" ProtoBuf 解压缩并反序列化开始:" + begin.ToString("yyyy-MM-dd HH:mm:ss"));
try
{
int bufferSize = 40960;
//打开文件
FileStream fs = File.OpenRead(@"E:\testdata1\Record4.zip");
//设置文件流的位置
fs.Position = 0;
//通过ZIpInputStream得到zip文件的对象
ZipInputStream zipInputStream = new ZipInputStream(fs, bufferSize);
//通过zip.getNextEntry()来得到ZipEntry对象
zipInputStream.GetNextEntry();
//定义数据缓冲
byte[] buffer = new byte[bufferSize];
//定义读取位置
int offset = 0;
//定义内存流
MemoryStream ms = new MemoryStream();
while ((offset = zipInputStream.Read(buffer, 0, buffer.Length)) != 0)
{
//解压后的数据写入内存流
ms.Write(buffer, 0, offset);
}
//设置内存流的位置
ms.Position = 0;
//ProtoBuf反序列化
this.requestList = ProtoBuf.Serializer.Deserialize<List<Request>>(ms);
ms.Close();
ms.Dispose();
//关闭流
fs.Close();
//释放对象
fs.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
DateTime end = DateTime.Now;
TimeSpan ts = end - begin;
Console.WriteLine(" ProtoBuf 解压缩并反序列化结束" + end.ToString("yyyy-MM-dd HH:mm:ss"));
Console.WriteLine("共花费" + ts.TotalSeconds);
foreach (Request p in requestList)
{
Console.WriteLine("Id:" + p.id + "密码:" + p.password);
}
}

效果

C#中使用SharpZipLib进行解压缩并使用ProtoBuf进行反序列化_C#