C# 文件压缩/解压方法

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;

namespace SYS_TEST.BaseClass
{
    //文件压缩/解压方法
    //引用ICSharpCode.SharpZipLib.dll
    public class ZIPClass
    {
        /// 
        /// 将目录中的文件压缩
        /// 
        /// 压缩后的文件
        /// 压缩文件目录
        /// 文件过滤
        public static void PackFiles(string zipFilename, string sourceDirectory, string fileFliter)
        {
            FastZip fz = new FastZip();
            fz.CreateEmptyDirectories = true;
            fz.CreateZip(zipFilename, sourceDirectory, false, fileFliter);
            fz = null;
        }
        /// 
        /// 解压缩文件
        /// 
        /// 待解压缩的文件
        /// 解压缩后文件存放的目录
        public static void UnpackFiles(string zipFile, string directory)
        {
            if (!Directory.Exists(directory))
                Directory.CreateDirectory(directory);

            ZipInputStream stream = new ZipInputStream(File.OpenRead(zipFile));
            ZipEntry theEntry = null;
            while ((theEntry = stream.GetNextEntry()) != null)
            {
                string directoryName = Path.GetDirectoryName(theEntry.Name);
                string fileName = Path.GetFileName(theEntry.Name);
                if (directoryName != string.Empty)
                    Directory.CreateDirectory(directory + directoryName);

                if (fileName != string.Empty)
                {
                    FileStream streamWriter = File.Create(Path.Combine(directory, theEntry.Name));
                    int size = 2048;
                    byte[] data = new byte[size];
                    while (true)
                    {
                        size = stream.Read(data, 0, data.Length);
                        if (size > 0)
                            streamWriter.Write(data, 0, size);
                        else
                            break;
                    }
                    streamWriter.Close();
                }
            }
            stream.Close();
        }
    }
}

你可能感兴趣的:(C#)