C#实现压缩和解压缩的方法示例【Gzip和Zip方式】
本文实例讲述了C#实现压缩和解压缩的方法。分享给大家供大家参考,具体如下:
使用ICSharpCode.SharpZipLib.dll来压缩/解压(压缩效率比GZip要高一点)
publicstaticclassZipUtil { //////压缩 /// ////// publicstaticstringCompress(stringparam) { byte[]data=System.Text.Encoding.UTF8.GetBytes(param); //byte[]data=Convert.FromBase64String(param); MemoryStreamms=newMemoryStream(); Streamstream=newICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(ms); try { stream.Write(data,0,data.Length); } finally { stream.Close(); ms.Close(); } returnConvert.ToBase64String(ms.ToArray()); } /// ///解压 /// ////// publicstaticstringDecompress(stringparam) { stringcommonString=""; byte[]buffer=Convert.FromBase64String(param); MemoryStreamms=newMemoryStream(buffer); Streamsm=newICSharpCode.SharpZipLib.BZip2.BZip2InputStream(ms); //这里要指明要读入的格式,要不就有乱码 StreamReaderreader=newStreamReader(sm,System.Text.Encoding.UTF8); try { commonString=reader.ReadToEnd(); } finally { sm.Close(); ms.Close(); } returncommonString; } }
使用GZip来压缩/解压缩(字符串)
publicstaticclassGZipUtil { publicstaticstringZip(stringvalue) { //Transformstringintobyte[] byte[]byteArray=newbyte[value.Length]; intindexBA=0; foreach(chariteminvalue.ToCharArray()) { byteArray[indexBA++]=(byte)item; } //Prepareforcompress System.IO.MemoryStreamms=newSystem.IO.MemoryStream(); System.IO.Compression.GZipStreamsw=newSystem.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress); //Compress sw.Write(byteArray,0,byteArray.Length); //Close,DONOTFLUSHcausebyteswillgomissing... sw.Close(); //Transformbyte[]zipdatatostring byteArray=ms.ToArray(); System.Text.StringBuildersB=newSystem.Text.StringBuilder(byteArray.Length); foreach(byteiteminbyteArray) { sB.Append((char)item); } ms.Close(); sw.Dispose(); ms.Dispose(); returnsB.ToString(); } publicstaticstringUnZip(stringvalue) { //Transformstringintobyte[] byte[]byteArray=newbyte[value.Length]; intindexBA=0; foreach(chariteminvalue.ToCharArray()) { byteArray[indexBA++]=(byte)item; } //Preparefordecompress System.IO.MemoryStreamms=newSystem.IO.MemoryStream(byteArray); System.IO.Compression.GZipStreamsr=newSystem.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress); //Resetvariabletocollectuncompressedresult byteArray=newbyte[byteArray.Length]; //Decompress intrByte=sr.Read(byteArray,0,byteArray.Length); //Transformbyte[]unzipdatatostring System.Text.StringBuildersB=newSystem.Text.StringBuilder(rByte); //ReadthenumberofbytesGZipStreamredanddonotaforeachbytesin //resultByteArray; for(inti=0;i更多关于C#相关内容感兴趣的读者可查看本站专题:《C#常见控件用法教程》、《WinForm控件用法总结》、《C#数据结构与算法教程》、《C#面向对象程序设计入门教程》及《C#程序设计之线程使用技巧总结》
希望本文所述对大家C#程序设计有所帮助。