2.文件夹及文件压缩

//调用

 string sourcePath = @"F:\zazhi\book\2013-09";

 zipfile.CompressDirector(sourcePath, sourcePath + ".zip", 9, 4096);

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;
using ICSharpCode.SharpZipLib.Zip;
using System.Diagnostics;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Checksums;
using System.IO.Packaging;
namespace WindowsFormsApplication1
{
    public class zipfile
    {

     #region 8 压缩文件夹
        ///
        /// 压缩文件夹
        ///
        /// 压缩文件夹的路径
        /// 生成的zip文件路径
        /// 压缩级别 0 - 9 0是存储级别 9是最大压缩
        /// 读取文件的缓冲区大小
        public static void CompressDirector(string dirPath, string fileName, int level, int bufferSize)
        {
            byte[] buffer = new byte[bufferSize];
            using (ZipOutputStream s = new ZipOutputStream(File.Create(fileName)))
            {
                s.SetLevel(level);
                CompressDirector(dirPath, dirPath, s, buffer);
                s.Finish();
                s.Close();
            }
        }

        ///
        /// 压缩文件夹
        ///
        /// 压缩文件夹路径
        /// 压缩文件夹内当前要压缩的文件夹路径
        ///
        /// 读取文件的缓冲区大小
        private static void CompressDirector(string root, string path, ZipOutputStream s, byte[] buffer)
        {
            root = root.TrimEnd('\\') + "\";
            string[] fileNames = Directory.GetFiles(path);
            string[] dirNames = Directory.GetDirectories(path);
            string relativePath = path.Replace(root, "");
            if (relativePath != "")
            {
                relativePath = relativePath.Replace("\", "/") + "/";
            }
            int sourceBytes;
            foreach (string file in fileNames)
            {

                ZipEntry entry = new ZipEntry(relativePath + Path.GetFileName(file));
                entry.DateTime = DateTime.Now;
                s.PutNextEntry(entry);
                using (FileStream fs = File.OpenRead(file))
                {
                    do
                    {
                        sourceBytes = fs.Read(buffer, 0, buffer.Length);
                        s.Write(buffer, 0, sourceBytes);
                    } while (sourceBytes > 0);
                }
            }

            foreach (string dirName in dirNames)
            {
                string relativeDirPath = dirName.Replace(root, "");
                ZipEntry entry = new ZipEntry(relativeDirPath.Replace("\", "/") + "/");
                s.PutNextEntry(entry);
                CompressDirector(root, dirName, s, buffer);
            }
        }
        #endregion

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值