标签归档:gzip

c#.net中使用GZipStream进行Gzip压缩

在抓取一些网站时,不论怎么改编码数据流都是乱码,这是就应该查看该网站是否用了gzip压缩(检测地址:http://tool.chinaz.com/Gzips/

再知道了该网址确实用了gzip压缩,就可以把他解压了,这样乱码的问题就解决了。

 

//压缩
         public void Compress(System.IO.Stream orgStream, System.IO.Stream cmpStream)
         {
             System.IO.Compression.GZipStream zipStream = new System.IO.Compression.GZipStream(cmpStream, System.IO.Compression.CompressionMode.Compress);
             BinaryWriter writer = new BinaryWriter(zipStream);
             BinaryReader reader = new BinaryReader(orgStream);
             while (true)
             {
                 byte[] buffer = reader.ReadBytes(100);
                 if (buffer == null || buffer.Length < 1)
                     break;
                 writer.Write(buffer);
             }
         }
 //解压缩
         public void DeCompress(System.IO.Stream cmpStream, System.IO.Stream orgStream)
         {
             System.IO.Compression.GZipStream zipStream = new System.IO.Compression.GZipStream(cmpStream, System.IO.Compression.CompressionMode.Decompress);
             BinaryReader reader = new BinaryReader(zipStream);
             BinaryWriter writer = new BinaryWriter(orgStream);
             while (true)
             {
                 byte[] buffer = reader.ReadBytes(100);
                 if (buffer == null || buffer.Length < 1)
                     break;
                 writer.Write(buffer);
             }
         }
 //执行压缩
         private void button1_Click(object sender, EventArgs e)
         {
             System.IO.FileStream targetstream = new System.IO.FileStream(this.txt_SelFile.Text, System.IO.FileMode.Open);
             System.IO.FileStream saveStream = new System.IO.FileStream(this.txt_SaveTo.Text, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Read);
             CompressionHelper.Compress(CompressionHelper.CompressionMode.GZip,targetstream, saveStream);
             targetstream.Close();
             saveStream.Close();
         }
 //执行解压缩
         private void button2_Click(object sender, EventArgs e)
         {
             System.IO.FileStream targetstream = new System.IO.FileStream(this.txt_SelFile.Text, System.IO.FileMode.Open);
             System.IO.FileStream saveStream = new System.IO.FileStream(this.txt_SaveTo.Text,System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.Read);
             CompressionHelper.DeCompress(CompressionHelper.CompressionMode.GZip , targetstream, saveStream);
             targetstream.Close();
             saveStream.Close();
         }