C#压缩与解压缩文件

ICSharpCode.SharpZipLib.dll 是一个开源的组件,提供了多种压缩算法的支持,可以利用它对多种文件格式进行压缩与解压缩。
下载网址:http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx
在项目中加入对ICSharpCode.SharpZipLib.dll的引用:

    /// <summary>
    /// 压缩文件
    /// </summary>
    /// <param name="savePath">保存压缩包的路径</param>
    /// <param name="fileNames">要压缩的文件名</param>
    public static void CompressFile(string savePath, params string[] fileNames)
    {
        ZipOutputStream stream = new ZipOutputStream(File.Create(savePath));
        stream.SetLevel(8);//设置压缩级别(0-9),值越大压缩越厉害
        //遍历所有要压缩的文件
        foreach (string fileName in fileNames)

        {
            if (File.Exists(fileName))
            {
                FileStream fs = File.OpenRead(fileName);
                byte[] buffer = new byte[fs.Length];//设置缓冲区大小
                int size = fs.Read(buffer, 0, buffer.Length); //读入缓冲区中的字节数
                string entryName = fileName.Substring(fileName.LastIndexOf("//") + 1);
                ZipEntry entry = new ZipEntry(entryName);
                stream.PutNextEntry(entry);
                stream.Write(buffer, 0, size);
                try
                {
                    //如果读入缓冲区中的字节数没有所请求的总字节数那么多
                    while (size < fs.Length)

                    {
                        int sizeRead = fs.Read(buffer, 0, buffer.Length);
                        stream.Write(buffer, 0, sizeRead);
                        size += sizeRead;
                    }
                }
                catch (Exception ex) { throw ex; }
                finally { fs.Close(); }
            }
        }
        stream.Finish();
        stream.Close();
    }
 

    /// <summary>  
    /// 解压缩文件  
    /// </summary>  
    /// <param name="packPath">压缩包路径</param> 
    /// <param name="saveDir">文件保存目录</param>        
    public static void DecompressFile(string packPath, string saveDir)

    {
        //目录不存在则创建
        if (!Directory.Exists(saveDir)) Directory.CreateDirectory(saveDir);
        int size = 2048;
        byte[] buffer = new byte[size];
        ZipInputStream stream = new ZipInputStream(File.OpenRead(packPath));
        //解压文件到指定的目录
        try
        {
            ZipEntry entry;
            while ((entry = stream.GetNextEntry()) != null)
            {
                FileStream fs = File.Create(saveDir +new Random().Next(100)+ entry.Name);
                while (true)
                {
                    size = stream.Read(buffer, 0, buffer.Length);
                    if (size <= 0) break//读到压缩文件尾
                    fs.Write(buffer, 0, size);
                }
                fs.Close();
            }
        }
        catch (Exception ex) { throw ex; }
        stream.Close();

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值