c#操作文件夹压缩到指定目录和解压到指定目录

调用类

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

namespace s
{
    public class ssss
    {
        public int avg = 1024 * 1024 * 100;//100MB写一次  

        #region 压缩文件 和 文件夹

        /// <summary>
        /// 压缩文件 和 文件夹
        /// </summary>
        /// <param name="FileToZip">待压缩的文件或文件夹,全路径格式</param>
        /// <param name="ZipedFile">压缩后生成的压缩文件名,全路径格式</param>
        /// <returns>压缩是否成功</returns>
        public bool Zip(string FileToZip, string ZipedFile)
        {

            return Zip(FileToZip, ZipedFile, "");

        }

        /// <summary>
        /// 压缩文件 和 文件夹,不压缩顶级目录
        /// </summary>
        /// <param name="FolderToZip">待压缩的文件夹,全路径格式</param>
        /// <param name="ZipedFile">压缩后生成的压缩文件名,全路径格式</param>
        /// <returns>压缩是否成功</returns>
        public  bool ZipNo(string FolderToZip, string ZipedFile)
        {
            if (!Directory.Exists(FolderToZip))
                return false;

            if (ZipedFile == string.Empty)
            {
                //如果为空则文件名为待压缩的文件名加上.rar
                ZipedFile = FolderToZip + ".zip";
            }
            ZipOutputStream s = new ZipOutputStream(File.Create(ZipedFile));
            s.SetLevel(6);
            string[] filenames = Directory.GetFiles(FolderToZip);
            ZipEntry entry = null;
            FileStream fs = null;
            Crc32 crc = new Crc32();
            foreach (string file in filenames)
            {
                //压缩文件
                fs = File.OpenRead(file);
                byte[] buffer = new byte[avg];
                entry = new ZipEntry(Path.GetFileName(file));
                entry.DateTime = DateTime.Now;
                entry.Size = fs.Length;
                s.PutNextEntry(entry);
                for (int i = 0; i < fs.Length; i += avg)
                {
                    if (i + avg > fs.Length)
                    {
                        //不足100MB的部分写剩余部分
                        buffer = new byte[fs.Length - i];
                    }
                    fs.Read(buffer, 0, buffer.Length);
                    s.Write(buffer, 0, buffer.Length);
                }
            }

            if (fs != null)
            {

                fs.Close();

                fs = null;

            }

            if (entry != null)

                entry = null;

            GC.Collect();

            GC.Collect(1);

            //压缩目录

            string[] folders = Directory.GetDirectories(FolderToZip);

            foreach (string folder in folders)
            {

     

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值