c#使用SharpZipLib對二進制數據進行壓縮和解壓


 

首先需要下載SharpZipLib,下載地址:http://icsharpcode.github.io/SharpZipLib/

需要引入命名空間:

 

[csharp] view plain copy
 
  1. using ICSharpCode.SharpZipLib.GZip;  
  2. using System.IO;  
壓縮:

 

[csharp] view plain copy
 
  1. public static byte[] CompressGZip(byte[] rawData)  
  2. {  
  3.     MemoryStream ms = new MemoryStream();  
  4.     GZipOutputStream compressedzipStream = new GZipOutputStream(ms);  
  5.     compressedzipStream.Write(rawData, 0, rawData.Length);  
  6.     compressedzipStream.Close();  
  7.     return ms.ToArray();  
  8. }  
解壓:

 

[csharp] view plain copy
 
  1. public static byte[] UnGZip(byte[] byteArray)   
  2. {   
  3.     GZipInputStream gzi = new GZipInputStream(new MemoryStream(byteArray));  
  4.       
  5.     MemoryStream re = new MemoryStream(50000);  
  6.     int count;  
  7.     byte[] data = new byte[50000];  
  8.     while ((count = gzi.Read(data, 0, data.Length)) != 0)  
  9.     {  
  10.         re.Write(data, 0, count);  
  11.     }  
  12.     byte[] overarr = re.ToArray();  
  13.     return overarr;   
  14. }   
測試:

 

[csharp] view plain copy
 
  1. public static void GZipTest()  
  2.     {  
  3.         string testdata = "aaaa11233GZip壓縮和解壓";  
  4.   
  5.         byte[] gzipdata = Tools.CompressGZip(Encoding.UTF8.GetBytes(testdata));  
  6.         byte[] undata = Tools.UnGZip(gzipdata);  
  7.   
  8.         Debug.Log("[GZipTest]  : data" + Encoding.UTF8.GetString(undata));  
  9.     }  
結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM