ICSharpCode.SharpZLib的使用记录

====同事指点的==================

 private void StartZip(string fileName, string sourceFolderPath, string targetPath)
        {
            try
            {
               // linkLabel1.Text = "";

                string tempDirectory = System.IO.Path.GetTempPath() + "\\";
                string tempFilename = "_" + DateTime.Now.ToString("yyyyMMddhhmmss") + fileName.Trim();
                using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(tempDirectory + tempFilename)))
                {
                    // store only
                    zipStream.SetLevel(0);

                    // Disable Zip64 for Mac compatibility
                    zipStream.UseZip64 = UseZip64.Off;

                    string path = sourceFolderPath;

                    // This setting will strip the leading part of the folder path in the entries, to
                    // make the entries relative to the starting folder.
                    // To include the full path for each entry up to the drive root, assign folderOffset = 0.
                    int folderOffset = path.Length + (path.EndsWith("\\") ? 0 : 1);

                    AddZipEntry(path, zipStream, folderOffset);

                    zipStream.Finish();
                    zipStream.Close();
                }

                FileInfo zipFile = new FileInfo(tempDirectory + tempFilename);
                if (zipFile.Exists)
                {
                    string destDirectory = targetPath;
                    if (!destDirectory.EndsWith("\\"))
                    {
                        destDirectory += "\\";
                    }
                    string destFile = fileName;
                    _zipDestPath = destDirectory + destFile;

                    zipFile.CopyTo(_zipDestPath);

                    //linkLabel1.Text = "Completed. Click here to show zip file.";
                    //linkLabel1.Click += new EventHandler(linkLabel1_Click);
                }
            }
            catch (Exception ex)
            {
                //linkLabel1.Text = "Errors encountered. Cannot continue. " + ex.InnerException;
            }
        }


 private void AddZipEntry(string path, ZipOutputStream zipStream, int folderOffset)
        {
            string[] files = Directory.GetFiles(path);
            foreach (string filename in files)
            {
                FileInfo fi = new FileInfo(filename);
                string entryName = filename.Substring(folderOffset); // Makes the name in zip based on the folder
                entryName = ZipEntry.CleanName(entryName); // Removes drive from name and fixes slash direction
                ZipEntry newEntry = new ZipEntry(entryName);
                newEntry.DateTime = fi.LastWriteTime; // Note the zip format stores 2 second granularity
                newEntry.Size = fi.Length;
                newEntry.CompressionMethod = CompressionMethod.Stored;

                zipStream.PutNextEntry(newEntry);

                // Zip the file in buffered chunks
                // the "using" will close the stream even if an exception occurs
                byte[] buffer = new byte[4096];
                using (FileStream streamReader = File.OpenRead(filename))
                {
                    StreamUtils.Copy(streamReader, zipStream, buffer);
                }

                zipStream.CloseEntry();
            }

            string[] folders = Directory.GetDirectories(path);
            foreach (string folder in folders)
            {
                AddZipEntry(folder, zipStream, folderOffset);
            }
        }


====以下是转的==================

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using System.Diagnostics;
using ICSharpCode.SharpZipLib.Core;


namespace TestConsole
{
    class Program
    {
        static string path = @"H:\New folder\folder\";


        static void Main()
        {
            CreateZipFile(@"H:\New folder\folder", @"H:\New folder\folder.zip");
            //UnZipFile(@"d:\a.zip");
        }


        private static void CreateZipFile(string filesPath, string zipFilePath)
        {
            ZipOutputStream u = new ZipOutputStream(File.Create(zipFilePath));            //新建压缩文件流 “ZipOutputStream”


            AddZipEntry(filesPath, u, out u); //向压缩文件流加入内容


            u.Finish(); // 结束压缩
            u.Close();
        }


        //添加压缩项目:p 为需压缩的文件或文件夹; u 为现有的源ZipOutputStream;  out j为已添加“ZipEntry”的“ZipOutputStream”
        public static void AddZipEntry(string p, ZipOutputStream u, out ZipOutputStream j)
        {
            string s = p;
            if (Directory.Exists(s))  //文件夹的处理
            {
                DirectoryInfo di = new DirectoryInfo(s);


                var tempd = di.GetDirectories();


                //***********以下内容是修订后添加的***********
                if (tempd.Length <= 0)   //没有子目录
                {
                    ZipEntry z = new ZipEntry(ShortDir(p) + "//"); //末尾“//”用于文件夹的标记
                    //u.PutNextEntry(z);
                }
                //***************以上内容是修订后添加的***************


                foreach (DirectoryInfo tem in tempd)  //获取子目录
                {
                    ZipEntry z = new ZipEntry(ShortDir(tem.FullName)); //末尾“//”用于文件夹的标记
                    //u.PutNextEntry(z);    //此句不可少,否则空目录不会被添加
                    s = tem.FullName;
                    AddZipEntry(s, u, out u);       //递归
                }


                var t = di.GetFiles();


                foreach (FileInfo temp in t)  //获取此目录的文件
                {
                    s = temp.FullName;
                    AddZipEntry(s, u, out u);      //递归
                }
            }
            else if (File.Exists(s))  //文件的处理
            {
                u.SetLevel(0);      //压缩等级
                FileStream f = File.OpenRead(s);
                byte[] b = new byte[f.Length];
                f.Read(b, 0, b.Length);          //将文件流加入缓冲字节中
                ZipEntry z = new ZipEntry(ShortDir(s));
                u.PutNextEntry(z);             //为压缩文件流提供一个容器
                u.Write(b, 0, b.Length);  //写入字节
                f.Close();
            }
            j = u;    //返回已添加数据的“ZipOutputStream”
        }


        private static string ShortDir(string s)
        {
            //将文件的绝对路径转为相对路径
            string d = s.Replace(path, "");
            return d;
        }
    }


}


========================这个最简单============================

解压缩代码:
using System;
using System.Collections.Generic;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;
using System.IO;
namespace DRMEncryption
{
    /// ;summary;
    /// UnZip 类用于解压缩一个 zip 文件。
    /// ;/summary;
    public class UnZipDir
    {
     //解压缩以后的文件名和路径,压缩前的路径
        public static Boolean UNZipFile(string FileToZip, string ZipedFile)
        {
            try
            {
                FastZip fastZip = new FastZip();
                fastZip.ExtractZip(FileToZip, ZipedFile, "");
                return true;
            }
            catch { 
                return false; 
            }
        }
}
}
压缩文件代码:
using System;
using System.IO;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.GZip;

namespace DRMEncryption
{
    public class ZipClass
    {
public static Boolean ZipFile(string FileToZip, string ZipedFile)
        {
            try
            {
                FastZip fastZip = new FastZip();
                
                bool recurse = true;
               //压缩后的文件名,压缩目录 ,是否递归          
             fastZip.CreateZip(FileToZip, ZipedFile, recurse, "");
                return true;
            }
            catch { return false; }
        
        }
    }
}
那个返回方法是用来另外一个页面判断解压是否成功用的,可以不要;
解压缩:UnZipDir.UNZipFile(文件名, 路径);
压缩:ZipClass.ZipFile(文件名, 路径);


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值