加压和解压

  using (FileStream freader = new FileStream("1.txt", FileMode.OpenOrCreate))
            {
                //写入文件的流
                using (FileStream fwrite = File.OpenWrite("1.rar"))//这里rar代表压缩,这里可以不写rar
                { 
                    // 根据写入流创建压缩流
                    using (GZipStream zip = new GZipStream(fwrite, CompressionMode.Compress))
                    {byte[] buffe = new byte[1024 * 5];//缓冲区
                        int r;
                        while ((r = freader.Read(buffe, 0, buffe.Length)) > 0)
                        {
                            zip.Write(buffe, 0, r);//用压缩流写入  r个实际的byte
                        }
                    }
                }
            }
          
            Console.Write("压缩ok");

解压

  //  读取文件的流
            using (FileStream fsreader = File.Open("1.rar", FileMode.Open))//这里1.rar代表压缩的文件
            {
                //  根据读取文件的流创建 压缩流,fsreader是压缩的流
                using (GZipStream zipSteam = new GZipStream(fsreader, CompressionMode.Decompress))
                {
                    //   写入流
                    using (FileStream fsWrite = File.OpenWrite("jie.txt"))
                    {
                        byte[] buffer = new byte[1024 * 3];
                        int r;
                        //  压缩流读取(压缩的文件)
                        while ((r = zipSteam.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            //  写入流写入(写入正常的)
                            fsWrite.Write(buffer, 0, r);
                        }
                    }
                }
            }

 

posted @ 2016-01-25 18:57  南潇湘  阅读(274)  评论(0编辑  收藏  举报