C#压缩与解压缩流类 GZipStream 的使用

  在使用 GZipStream 进行压缩的时候, 在最后必须调用 Close()方法, 否则会发现解压缩后少一个字节, 当压缩的文件小于4kb时, 解压缩到文件长度为0.

  下面为一个完整的压缩与解压缩文件的代码, 以做参考:

        private void button1_Click(object sender, EventArgs e)
        {
            string fileName = textBox1.Text; // @"f:\response.txt";

            FileInfo fi = new FileInfo(fileName);
            listBox1.Items.Add("source file length: " + fi.Length.ToString());
            byte[] buf = Compress(fileName);

            listBox1.Items.Add(String.Format("compress length: {0}, compress rate: {1:f2}%" ,buf.Length, (double)buf.Length * 100 / (double)fi.Length));

            string newFileName = String.Format(@"{0}\{1}_new{2}", 
                Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName), Path.GetExtension(fileName)); 
            listBox1.Items.Add("decompress length: " + Decompress(buf, newFileName).ToString());
        }

        public static byte[] Compress(string fileName)
        {
            //压缩后的MemoryStream
            MemoryStream ms = new MemoryStream();
            // 写入压缩
            GZipStream compressedStream = new GZipStream(ms, CompressionMode.Compress, true);
            FileStream fs = new FileStream(fileName, FileMode.Open);
            byte[] buf = new byte[1024];
            int count = 0;
            do
            {
                count = fs.Read(buf, 0, buf.Length);
                compressedStream.Write(buf, 0, count);
            }
            while (count > 0);

            fs.Close();            
            compressedStream.Close();

            return ms.ToArray();
        }


        public static int Decompress(byte[] data, string fileName)
        {
            int iRet = 0;
            byte[] buf = new byte[1024 * 1024];
            try
            {
                FileStream fs = new FileStream(fileName, FileMode.Create);

                MemoryStream ms = new MemoryStream(data);
                GZipStream decompressedStream = new GZipStream(ms, CompressionMode.Decompress,true);

                int count = 0;
                do
                {
                    count = decompressedStream.Read(buf, 0, buf.Length);
                    fs.Write(buf, 0, count);
                    fs.Flush();
                }
                while (count > 0);               
                
                iRet = (int)fs.Length;
                fs.Close();
            }
            finally
            {

            }
            return iRet;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog()
            {
                InitialDirectory = Environment.CurrentDirectory,
                Multiselect = false,
            };
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = dialog.FileName;
            }
        } 

 

posted @ 2012-06-04 11:43  沧海小小粟  阅读(9685)  评论(2编辑  收藏  举报