压缩和解压缩,分别引用开源的SharpZip 和 .net2005的Gzip

来源:互联网 发布:黑马程序员19期 编辑:程序博客网 时间:2024/05/20 19:15


2种 分别引用开源的SharpZip 和 .net2005的Gzip

public static class CompressDeCompress
    {
        //压缩SharpZip
        public static string SharpZipCompress(string uncompressedString)
        {
            byte[] bytData = System.Text.Encoding.Unicode.GetBytes(uncompressedString);
            MemoryStream ms = new MemoryStream();
            Stream s = new BZip2OutputStream(ms);
            s.Write(bytData, 0, bytData.Length);
            s.Close();
            byte[] compressedData = (byte[])ms.ToArray();
            return System.Convert.ToBase64String(compressedData, 0, compressedData.Length);
        }
        //解压SharpZip
        public static string SharpZipDeCompress(string compressedString)
        {
            System.Text.StringBuilder uncompressedString = new System.Text.StringBuilder();
            int totalLength = 0;
            byte[] bytInput = System.Convert.FromBase64String(compressedString); ;
            byte[] writeData = new byte[4096];
            Stream s2 = new BZip2InputStream(new MemoryStream(bytInput));
            while (true)
            {
                int size = s2.Read(writeData, 0, writeData.Length);
                if (size > 0)
                {
                    totalLength += size;
                    uncompressedString.Append(System.Text.Encoding.Unicode.GetString(writeData, 0, size));
                }
                else
                {
                    break;
                }
            }
            s2.Close();
            return uncompressedString.ToString();
        }
        压缩Gzip
        public static string GzipCompress(string uncompressedString)
        {
            byte[] bytData = System.Text.Encoding.Unicode.GetBytes(uncompressedString);
            MemoryStream ms = new MemoryStream();
            Stream s = new GZipStream(ms, CompressionMode.Compress);
            s.Write(bytData, 0, bytData.Length);
            s.Close();
            byte[] compressedData = (byte[])ms.ToArray();
            return System.Convert.ToBase64String(compressedData, 0, compressedData.Length);
        }
        //解压Gzip
        public static string GzipDeCompress(string compressedString)
        {
            System.Text.StringBuilder uncompressedString = new System.Text.StringBuilder();
            int totalLength = 0;
            byte[] bytInput = System.Convert.FromBase64String(compressedString); ;
            byte[] writeData = new byte[4096];
            Stream s2 = new GZipStream(new MemoryStream(bytInput), CompressionMode.Decompress);
            while (true)
            {
                int size = s2.Read(writeData, 0, writeData.Length);
                if (size > 0)
                {
                    totalLength += size;
                    uncompressedString.Append(System.Text.Encoding.Unicode.GetString(writeData, 0, size));
                }
                else
                {
                    break;
                }
            }
            s2.Close();
            return uncompressedString.ToString();
        }
    }


using ICSharpCode.SharpZipLib.BZip2;   //SharpZip 的命名空间
using System.IO.Compression;           //Gzip 的命名空间
具体Gzip用法可以查询msdn
 

我用web service,传输正常:
public DataSet DecompressDS(byte[] byt)
{
MemoryStream ms = new MemoryStream(byt);
BinaryFormatter bf = new BinaryFormatter();
ZipInputStream zis = new ZipInputStream(ms);
zis.GetNextEntry(); 
DataSetSurrogate dss = (DataSetSurrogate)bf.Deserialize(zis);
zis.Close();
ms.Close();
DataSet ds = dss.ConvertToDataSet();
return ds;
}

public static byte[] CompressDS(DataSet ds)
{
MemoryStream ms = new MemoryStream();
ZipOutputStream zos = new ZipOutputStream(ms);
zos.PutNextEntry(new ZipEntry(ds.DataSetName));  
BinaryFormatter bf = new BinaryFormatter();
DataSetSurrogate dss = new DataSetSurrogate(ds);
bf.Serialize(zos, dss);
zos.CloseEntry();
zos.Close();
byte[] ret = ms.ToArray();  
ms.Close();
return ret;
}


使用ICSharpCode.SharpZipLib.dll;
下载地址
http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx

下面是对#ZipLib进行.net下的解压缩的方法的介绍。

   1.BZip2
    加入ICSharpCode.SharpZipLib.dll的引用,在#Develop的安装目录下的/SharpDevelop/bin目录下。然后在程序中使用using语句把BZip2

类库包含进来。
压缩:使用BZip2的静态方法Compress。
    它的第一个参数是所要压缩的文件所代表的输入流,可以使用System.IO.File的静态方法OpenRead。
    第二个参数是要建立的压缩文件所代表的输出流,可以使用System.IO.File的静态方法Create创建,压缩文件名是所要压缩文件的文件名

加上压缩后缀.bz(同样你也可以取其他的文件名)。
    第三个参数是要压缩的块大小(一般为2048的整数)。

解压:使用BZip2的静态方法Decompress。
    它的第一个参数是所要解压的压缩文件所代表的输入流,可以使用System.IO.File的静态方法OpenRead。
    第二个参数是要建立的解压文件所代表的输出流,可以使用System.IO.File的静态方法Create创建,因为解压文件的文件名是去掉了压缩

文件扩展名的压缩文件名(你也可以做成解压文件与压缩文件不同名的)。
编译你的程序,然后在命令行方式下输入bzip2 文件名(假设建立的C#文件是bzip2,就可以生成压缩文件;输入bzip2 -d 文件名,就会解压

出文件来(-d是用来表示解压,你也可以使用其他的符号)。
呵呵,原来做压缩可以这么简单的,压缩效果也可以啊。
using System;
using System.IO;
using ICSharpCode.SharpZipLib.BZip2;

class MainClass
{
   public static void Main(string[] args)
   {
      if (args[0] == "-d") { // 解压
         BZip2.Decompress(File.OpenRead(args[1]), File.Create(Path.GetFileNameWithoutExtension(args[1])));
      } else { //压缩
         BZip2.Compress(File.OpenRead(args[0]), File.Create(args[0] + ".bz"), 4096);
      }
   }
}
2.GZip 
   加入ICSharpCode.SharpZipLib.dll的引用,在#Develop的安装目录下的/SharpDevelop/bin目录下。然后在程序中使用using语句把GZip类

库包含进来。 
   由于GZip没有BZip2的简单解压缩方法,因此只能使用流方法来进行解压缩。具体的方法见程序的说明。
   编译程序,然后在命令行方式下输入GZip 文件名(假设建立的C#文件是GZip,就可以生成压缩文件;输入GZip -d 文件名,就会解压出文

件来(-d是用来表示解压,你也可以使用其他的符号)。 

using System;
using System.IO;

using ICSharpCode.SharpZipLib.GZip;

class MainClass
{
   public static void Main(string[] args)
   {
      if (args[0] == "-d") { // 解压
         Stream s = new GZipInputStream(File.OpenRead(args[1]));
         //生成一个GZipInputStream流,用来打开压缩文件。
        //因为GZipInputStream由Stream派生,所以它可以赋给Stream。
          //它的构造函数的参数是一个表示要解压的压缩文件所代表的文件流
         FileStream fs = File.Create(Path.GetFileNameWithoutExtension(args[1]));
         //生成一个文件流,它用来生成解压文件
         //可以使用System.IO.File的静态函数Create来生成文件流
         int size = 2048;//指定压缩块的大小,一般为2048的倍数
         byte[] writeData = new byte[size];//指定缓冲区的大小
         while (true) {
            size = s.Read(writeData, 0, size);//读入一个压缩块
            if (size > 0) {
               fs.Write(writeData, 0, size);//写入解压文件代表的文件流
            } else {
               break;//若读到压缩文件尾,则结束
            }
         }
         s.Close();
      } else { // 压缩
         Stream s = new GZipOutputStream(File.Create(args[0] + ".gz"));
         //生成一个GZipOutputStream流,用来生成压缩文件。
                        //因为GZipOutputStream由Stream派生,所以它可以赋给Stream。
          FileStream fs = File.OpenRead(args[0]);
         /生成一个文件流,它用来打开要压缩的文件
         //可以使用System.IO.File的静态函数OpenRead来生成文件流
         byte[] writeData = new byte[fs.Length];
         //指定缓冲区的大小
         fs.Read(writeData, 0, (int)fs.Length);
         //读入文件
         s.Write(writeData, 0, writeData.Length);
         //写入压缩文件
         s.Close();
         //关闭文件
      }
   }
}


using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.Compression;
using System.Windows.Forms;

namespace CompressionSample
{
    class ZipUtil
    {
        public void CompressFile ( string sourceFile, string destinationFile )
        {
            // make sure the source file is there
            if ( File.Exists ( sourceFile ) == false )
                throw new FileNotFoundException ( );

            // Create the streams and byte arrays needed
            byte[] buffer = null;
            FileStream sourceStream = null;
            FileStream destinationStream = null;
            GZipStream compressedStream = null;

            try
            {
                // Read the bytes from the source file into a byte array
                sourceStream = new FileStream ( sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read );

                // Read the source stream values into the buffer
                buffer = new byte[sourceStream.Length];
                int checkCounter = sourceStream.Read ( buffer, 0, buffer.Length );

                if ( checkCounter != buffer.Length )
                {
                    throw new ApplicationException ( );
                }

                // Open the FileStream to write to
                destinationStream = new FileStream ( destinationFile, FileMode.OpenOrCreate, FileAccess.Write );

                // Create a compression stream pointing to the destiantion stream
                compressedStream = new GZipStream ( destinationStream, CompressionMode.Compress, true );

                // Now write the compressed data to the destination file
                compressedStream.Write ( buffer, 0, buffer.Length );
            }
            catch ( ApplicationException ex )
            {
                MessageBox.Show ( ex.Message, "An Error occured during compression", MessageBoxButtons.OK, MessageBoxIcon.Error );
            }
            finally
            {
                // Make sure we allways close all streams
                if ( sourceStream != null )
                    sourceStream.Close ( );

                if ( compressedStream != null )
                    compressedStream.Close ( );

                if ( destinationStream != null )
                    destinationStream.Close ( );
            }
        }

        public void DecompressFile ( string sourceFile, string destinationFile )
        {
            // make sure the source file is there
            if ( File.Exists ( sourceFile ) == false )
                throw new FileNotFoundException ( );

            // Create the streams and byte arrays needed
            FileStream sourceStream = null;
            FileStream destinationStream = null;
            GZipStream decompressedStream = null;
            byte[] quartetBuffer = null;

            try
            {
                // Read in the compressed source stream
                sourceStream = new FileStream ( sourceFile, FileMode.Open );

                // Create a compression stream pointing to the destiantion stream
                decompressedStream = new GZipStream ( sourceStream, CompressionMode.Decompress, true );

                // Read the footer to determine the length of the destiantion file
                quartetBuffer = new byte[4];
                int position = (int)sourceStream.Length - 4;
                sourceStream.Position = position;
                sourceStream.Read ( quartetBuffer, 0, 4 );
                sourceStream.Position = 0;
                int checkLength = BitConverter.ToInt32 ( quartetBuffer, 0 );

                byte[] buffer = new byte[checkLength + 100];

                int offset = 0;
                int total = 0;

                // Read the compressed data into the buffer
                while ( true )
                {
                    int bytesRead = decompressedStream.Read ( buffer, offset, 100 );

                    if ( bytesRead == 0 )
                        break;

                    offset += bytesRead;
                    total += bytesRead;
                }

                // Now write everything to the destination file
                destinationStream = new FileStream ( destinationFile, FileMode.Create );
                destinationStream.Write ( buffer, 0, total );

                // and flush everyhting to clean out the buffer
                destinationStream.Flush ( );
            }
            catch ( ApplicationException ex )
            {
                MessageBox.Show ( ex.Message, "An Error occured during compression", MessageBoxButtons.OK, MessageBoxIcon.Error );
            }
            finally
            {
                // Make sure we allways close all streams
                if ( sourceStream != null )
                    sourceStream.Close ( );

                if ( decompressedStream != null )
                    decompressedStream.Close ( );

                if ( destinationStream != null )
                    destinationStream.Close ( );
            }

        }
    }
}

原创粉丝点击