GzipStream的简单使用压缩和解压

压缩和解压都需要用到三个流实例,分别是文件读取流、文件写入流、压缩流。

读取流和写入流有多种形式,压缩流就一种GzipStream。

不同的是对于压缩,是需要用文件写入流作为创建压缩流实例的参数,

压缩时是通过文件读取流读取文件,压缩流写入文件,这样就完成了压缩。

解压,是需要用文件读取流为参数创建压缩流实例,

通过压缩读取流读取文件,再通过文件写入流写入文件,这样就完成了解压。

这里解析一个枚举CompressionMode,它有两个值分别是Compress、DeCompress。

表示压缩和解压,在创建压缩流实例的时候会用到。

代码解析

压缩

            //1.创建读取文本文件的流
            using (FileStream fsRead = File.OpenRead("1.txt"))
            {
                //2.创建写文件流
                using (FileStream fsWrite = File.OpenWrite(@"C:UsersjohnDesktopyasuo.rar"))
                {
                    //3.创建压缩流
                    using (GZipStream zipStream = new GZipStream(fsWrite, CompressionMode.Compress))
                    {     
                        byte[] byts = new byte[1024];
                        int len = 0;
                        //4.通过读取文件流读取数据
                        while ((len = fsRead.Read(byts, 0, byts.Length)) > 0)
                        {
                            
                                //通过压缩流写入数据
                                zipStream.Write(byts, 0, len);
                            
                        }
                    }
                }
            }

  解压

            //1.创建读取流
            using (FileStream fsRead = File.OpenRead(@"C:UsersjohnDesktopyasuo.rar"))
            {
                //2.创建压缩流,把读取流作为参数,
                using (GZipStream zip = new GZipStream(fsRead, CompressionMode.Decompress))
                {
                    //创建写入流
                    using (FileStream fsWrite=File.OpenWrite(@"C:UsersjohnDesktop1.txt"))
                    {
                        byte[] byts = new byte[1024];
                        int len = 0;//用于表示真是接受到是字节个数
                        //通过压缩流读取数据
                        while ((len=zip.Read(byts,0,byts.Length))>0)
                        {
                            //MessageBox.Show(Encoding.UTF8.GetString(byts.Take(len).ToArray()));
                            //通过文件流写入文件
                            fsWrite.Write(byts, 0, len);//读取的长度为len,这样不会造成数据的错误
                        }
                    }
                }

            }
原文地址:https://www.cnblogs.com/xiaoai123/p/6883733.html