blueyund

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
.NET 2.0 支援 System.IO.Compression 名称空间,其中定义了 GZipStream 类别来压缩和解压缩 Stream 资料。GZipStream 继承至 Stream 类别,所以该类别使用和一版的 Stream 类别相仿。下面是 对  Stream 压缩和解压缩的范例: 
using System;
using System.IO;
using System.IO.Compression;

namespace gzipTest {
    class Program {
        static void Main(string[] args) {
            GZipTest.Compress("c:\\vcredist_x86.exe", "c:\\vcredist_x86.exe.zip");
            GZipTest.Decompress("c:\\vcredist_x86.exe.zip", "c:\\vcredist_x86.exe.zip.exe");
        }
    }

    public class GZipTest{
        const int SIZE = 4096;
        public static void Compress(String from, String to){
           
            using (FileStream fs = new FileStream(from, FileMode.Open)) {
                using (FileStream fsOutput = new FileStream(to, FileMode.Create, FileAccess.Write)) {                                      
                    using (GZipStream zip = new GZipStream(fsOutput, CompressionMode.Compress)) {
                        byte[] input = new byte[SIZE];
                        int bytesRead;
                        while ((bytesRead = fs.Read(input, 0, SIZE)) > 0) {                           
                            zip.Write(input, 0, bytesRead);
                                                   
                        }
                    }
                }
            }
        }

        public static void Decompress(String from, String to) {
            using (FileStream fs = new FileStream(from, FileMode.Open)) {
                using (FileStream fsOutput = new FileStream(to, FileMode.Create, FileAccess.Write)) {
                    using (GZipStream zip = new GZipStream(fs, CompressionMode.Decompress, true)) {
                        byte[] buffer = new byte[SIZE];
                        int bytesRead;
                        while ((bytesRead = zip.Read(buffer, 0, buffer.Length)) > 0) {
                            fsOutput.Write(buffer, 0, bytesRead);
                        }
                    }
                } 
            }
        }
    }
}

 

posted on 2008-09-21 12:49  blueyund  阅读(495)  评论(0编辑  收藏  举报