文件压缩和解压 FileStream GZipStream

  using (FileStream reader=new FileStream (@"c:\1.txt",FileMode.Open,FileAccess.Read))
            {
                using (FileStream writer=new FileStream (@"c:\4.zp",FileMode.OpenOrCreate,FileAccess.Write))
                {
                    //压缩写的流
                    using (GZipStream zip=new GZipStream (writer,CompressionMode.Compress))
                    {
                        byte[] buffer = new byte[12];
                        int r = 0;
                        while ((r=reader.Read(buffer,0,buffer.Length))>0)
                        {
                            //压缩写入
                            zip.Write(buffer,0,r);
                            
                        }
                    }
                }
            }
            Console.WriteLine("/压缩完成");

            using (FileStream reader = new FileStream(@"c:\4.zp", FileMode.OpenOrCreate, FileAccess.Read))
            {
                using (FileStream writer = new FileStream(@"c:\5.txt", FileMode.OpenOrCreate, FileAccess.Write))
                {
                    byte[] buffer = new byte[13];
                    //解压读的流 因读的是压缩文件,reader读出的是压缩后的流
                    using (GZipStream zip = new GZipStream(reader, CompressionMode.Decompress))
                    {
                        int r=0;
                        
                        while ((r = zip.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            //正常的流写入
                            writer.Write(buffer, 0, r);
                        }
                    }

                }
            }

这种压缩只能实现单个文件的压缩和解压,多个文件的暂时不能使用

posted @ 2017-03-16 13:10  南潇湘  阅读(513)  评论(0编辑  收藏  举报