一。压缩文件,生成文件流

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

namespace TimeInterval
{
    public class ZipFileBuilder : IDisposable
    {
        private bool disposed = false;
        ZipOutputStream zipStream = null;

        protected ZipOutputStream ZipStream
        {
            get { return zipStream; }
        }

        ZipEntryFactory factory = null;
        private ZipEntryFactory Factory
        {
            get { return factory; }
        }

        public ZipFileBuilder(Stream outStream)
        {
            zipStream = new ZipOutputStream(outStream);
            zipStream.SetLevel(9); //best compression
            factory = new ZipEntryFactory(DateTime.Now);
        }

        public void Add(string fileName, Stream fileStream)
        {
            //create a new zip entry
            ZipEntry entry = factory.MakeFileEntry(fileName);
            entry.DateTime = DateTime.Now;
            ZipStream.PutNextEntry(entry);
            byte[] buffer = new byte[65536];

            int sourceBytes;
            do
            {
                sourceBytes = fileStream.Read(buffer, 0, buffer.Length);
                ZipStream.Write(buffer, 0, sourceBytes);
            }
            while (sourceBytes > 0);
        }

        public void AddDirectory(string directoryName)
        {
            ZipEntry entry = factory.MakeDirectoryEntry(directoryName);
            ZipStream.PutNextEntry(entry);
        }

        public void Finish()
        {
            if (!ZipStream.IsFinished)
            {
                ZipStream.Finish();
            }
        }

        public void Close()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public void Dispose()
        {
            this.Close();
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    if (ZipStream != null)
                        ZipStream.Dispose();
                }
            }

            disposed = true;
        }
    }
}
 #region ZIP

            using (MemoryStream ms = new MemoryStream())
            {
                using (ZipFileBuilder builder = new ZipFileBuilder(ms))
                {
                    AddFile(builder, @"D:\Cadence\A202.xls", @"D:\Cadence\");
                }
          //文件流写入zip文件
                FileStream fs = new FileStream(@"d:\Cadence\ZipFile.zip", FileMode.OpenOrCreate);
                BinaryWriter w = new BinaryWriter(fs);
                w.Write(ms.ToArray());
                fs.Close();
                ms.Close();
            }

            #endregion

 

二。包括压缩和解压缩

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

namespace LicenseMaintenance
{
    public class CZip:ICompress      
    {
        private Exception _ex;
        private int  bufflen=4096;

        public CZip()
        {
        }
        
        /// <summary>
        /// 取出当前文件目录中的所有子目录
        /// </summary>
        /// <param name="dir">当前目录对象</param>
        /// <param name="fis">子目录列表</param>
        protected void Found(DirectoryInfo dir, List<DirectoryInfo> fis)
        {
            if (dir == null) return;
            fis.Add(dir);
            DirectoryInfo[] dirs = dir.GetDirectories();
            foreach (DirectoryInfo item in dirs)
                Found(item, fis);
        }
        
        /// <summary>
        /// 取得目标文件的文件名
        /// </summary>
        /// <param name="srcpath">源文件路径</param>
        /// <param name="despath">目标文件路径</param>
        /// <returns></returns>
        protected string GetDesFile(string srcpath, string despath)
        {
            string desfile = Path.GetFileName(despath);
            string desdir = Path.GetDirectoryName(despath);

            if (string.IsNullOrEmpty(desfile))  //目标文件路路径中指定的文件名则直接返回,否则按以下方式读取
            {
                string srcfile = Path.GetFileName(srcpath);
                string srcdir = Path.GetDirectoryName(srcpath);
                if (!string.IsNullOrEmpty(srcfile)) //压缩单个文件时,取源文件名为目标文件名
                {
                    desfile = Path.GetFileNameWithoutExtension(srcfile) + ".zip";
                }
                else if (!Path.IsPathRooted(desdir))    //如果目标文件路径不是根目录名,取目标目录为文件名
                {
                    string[] str = desdir.Split(Path.DirectorySeparatorChar);
                    desfile = str[str.Length - 1] + ".zip";
                }
                else
                {
                    string[] str = srcdir.Split(Path.DirectorySeparatorChar);   //否则取原文件目录为目标文件名
                    desfile = str[str.Length - 1] + ".zip";
                }
            }
            return desfile;
        }

        #region ICompress Members

        //public bool CompressSingleFile(string filePath, string CompressFilepath)
        //{
        //    int cnt = 0;
        //    ZipOutputStream zipstream = null;
        //    Stream stream = null;
        //    BinaryReader sr = null;

        //    byte[] buffer = new byte[bufflen];

        //    try
        //    {
        //        stream = new FileStream(CompressFilepath, FileMode.OpenOrCreate);
        //        zipstream = new ZipOutputStream(stream);
        //        zipstream.UseZip64 = UseZip64.Off;
        //        //zipstream.Password = "";

        //        FileInfo f = new FileInfo(filePath);
        //        zipstream.PutNextEntry(new ZipEntry(f.Name.Replace(filePath, "")));
        //        sr = new BinaryReader(f.Open(FileMode.Open));
        //        while ((cnt = sr.Read(buffer, 0, bufflen)) > 0)
        //        {
        //            zipstream.Write(buffer, 0, cnt);
        //        }
        //        sr.Close();

        //        zipstream.Flush();
        //        zipstream.Close();
        //        stream.Close();
        //        return true;
        //    }
        //    catch (Exception e)
        //    {
        //        _ex = e;
        //    }
        //    return false;
        //}

        public bool CompressSingleFile(string filePath, string CompressFilepath)
        {
            try
            {
                if (File.Exists(CompressFilepath))
                {
                    using (ZipFile zip = new ZipFile(CompressFilepath))
                    {

                        zip.BeginUpdate();                                               

                        zip.Add(filePath);

                        zip.CommitUpdate();

                    }
                }
                else
                {
                    using (ZipFile zip = ZipFile.Create(CompressFilepath))
                    {

                        zip.BeginUpdate();

                        zip.Add(filePath);

                        zip.CommitUpdate();
                    }
                }

                return true;
            }
            catch (Exception e)
            {
                _ex = e;
            }
            return false;

            //int cnt = 0;                       

            //byte[] buffer = new byte[bufflen];

            //try
            //{

            //    using (ZipOutputStream zipstream = new ZipOutputStream(new FileStream(CompressFilepath, FileMode.OpenOrCreate)))
            //    {
            //        ZipEntry entry = null;
            //        zipstream.UseZip64 = UseZip64.Off;
            //        ZipInputStream p = new ZipInputStream(File.OpenRead(CompressFilepath));
            //        while ((entry = p.GetNextEntry()) != null)
            //        {
            //            ZipEntry zipEntry = new ZipEntry(entry.Name);
            //            //zipEntry.DateTime = DateTime.Now;
            //            zipstream.PutNextEntry(zipEntry);
            //            //byte[] buffer = new byte[204800];
            //            while ((cnt = p.Read(buffer, 0, bufflen)) > 0)
            //            {
            //                zipstream.Write(buffer, 0, cnt);
            //            }                        
            //        }                                        
                    
            //        FileInfo f = new FileInfo(filePath);
            //        zipstream.PutNextEntry(new ZipEntry(f.Name.Replace(filePath, "")));
            //        BinaryReader sr = null;
            //        sr = new BinaryReader(f.Open(FileMode.Open));
            //        while ((cnt = sr.Read(buffer, 0, bufflen)) > 0)
            //        {
            //            zipstream.Write(buffer, 0, cnt);
            //        }

            //        zipstream.Flush();
            //        zipstream.Close();
            //        p.Close();
            //        sr.Close();

            //    }
                
            //    return true;
            //}
            //catch (Exception e)
            //{
            //    _ex = e;
            //}
            //return false;
        } 

        /// <summary>
        /// 压缩方法
        /// </summary>
        /// <param name="srcpath">源文件路径</param>
        /// <param name="despath">目标文件路径</param>
        /// <returns></returns>
        public bool Compress(string srcpath, string despath)
        {
            return Compress(srcpath, despath,"");
        }
        /// <summary>
        /// 压缩方法
        /// </summary>
        /// <param name="srcpath">源文件路径</param>
        /// <param name="despath">目标文件路径</param>
        /// <param name="psw">密码</param>
        /// <returns></returns>
        public bool Compress(string srcpath, string despath, string psw)
        {
            int index = 0, cnt = 0;
            List<DirectoryInfo> list = new List<DirectoryInfo>();
            ZipOutputStream zipstream = null;
            Stream stream = null;
            BinaryReader sr = null;
            string srcdir = "", srcfile="";
            string desdir = Path.GetDirectoryName(despath);
            string desfile = "";
            byte[] buffer = new byte[bufflen];

            if (!File.Exists(srcpath) && !Directory.Exists(srcpath) ||
                string.IsNullOrEmpty(desdir))
            {
                _ex = new Exception("Invalid path.");
                return false;
            }
            if (File.Exists(srcpath))
            {
                srcdir = Path.GetDirectoryName(srcpath);
                srcfile = Path.GetFileName(srcpath);
            }
            else
            {
                srcdir = srcpath;
                srcfile = "";
            }

            desfile = GetDesFile(srcpath, despath);
            if (string.IsNullOrEmpty(desfile))
            {
                _ex = new Exception("Invalid target path.");
                return false;
            }
            try
            {

                if (!Directory.Exists(desdir))
                    Directory.CreateDirectory(desdir);

                Found(new DirectoryInfo(srcdir),list);
                stream = new FileStream(Path.Combine(desdir, desfile), FileMode.OpenOrCreate);
                zipstream = new ZipOutputStream(stream);
                zipstream.UseZip64 = UseZip64.Off;
                if (!string.IsNullOrEmpty(psw)) 
                    zipstream.Password = psw;

                foreach (DirectoryInfo item in list)
                {
                    string dir = Path.GetDirectoryName(item.FullName);
                    //zipstream.PutNextEntry(new ZipEntry(dir));
                    foreach (FileInfo f in item.GetFiles())
                    {
                        zipstream.PutNextEntry(new ZipEntry(f.Name.Replace(srcdir,"")));
                        sr = new BinaryReader(f.Open(FileMode.Open));
                        while ((cnt = sr.Read(buffer, 0, bufflen)) > 0)
                        {
                            zipstream.Write(buffer, 0, cnt);
                        }
                        sr.Close();
                    }
                   
                    
                }
                zipstream.Flush();
                zipstream.Close();
                stream.Close();
                return true;
            }
            catch (Exception e)
            {
                _ex = e;
            }
            return false;
        }
        /// <summary>
        /// 解压方法
        /// </summary>
        /// <param name="srcpath">源文件路径</param>
        /// <param name="despath">目标文件路径</param>
        /// <returns></returns>
        public bool UnCompress(string srcpath, string despath)
        {
            return UnCompress(srcpath, despath,"");
        }
        /// <summary>
        /// 解压方法
        /// </summary>
        /// <param name="srcpath">源文件路径</param>
        /// <param name="despath">目标文件路径</param>
        /// <param name="psw">密码</param>
        /// <returns></returns>
        public bool UnCompress(string srcpath, string despath, string psw)
        {
            int index = 0, cnt = 0;
            List<FileInfo> list = new List<FileInfo>();
            ZipInputStream zipstream = null;
            FileStream stream = null;
            byte[] buffer = new byte[bufflen];

            if (File.Exists(srcpath))
            {
                _ex = new System.IO.FileNotFoundException();
                return false;
            }
             
            string desdir=string.IsNullOrEmpty(despath) ? Directory.GetCurrentDirectory():Path.GetDirectoryName(despath);

            try
            {
                if (Directory.Exists(desdir))
                    Directory.CreateDirectory(desdir);

                stream = File.Open(srcpath, FileMode.Open);
                zipstream = new ZipInputStream(stream);
                ZipEntry entry =null;
                if (!string.IsNullOrEmpty(psw))
                zipstream.Password = psw;

                while ((entry = zipstream.GetNextEntry()) != null)
                {
                    if (entry.IsDirectory)
                    {
                        Directory.CreateDirectory(Path.Combine(desdir, entry.Name));
                    }
                    else if (entry.IsFile && entry.Crc != 0)
                    {
                        string desfile = Path.Combine(desdir, entry.Name);
                        using (FileStream sw = new FileStream(desfile, FileMode.OpenOrCreate))
                        {
                            while ((cnt = zipstream.Read(buffer, 0, bufflen)) > 0)
                            {
                                sw.Write(buffer, 0, cnt);
                            }
                            sw.Close();
                        }
                    }
                }
                zipstream.Close();
                stream.Close();
                return true;
            }
            catch (Exception e)
            {
                _ex = e;
            }
            return false;
        }
        /// <summary>
        /// 设置当前接口的执行参数
        /// </summary>
        /// <param name="key">键名</param>
        /// <param name="v"></param>
        public void SetArguments(string key, object v)
        {
            if (!string.IsNullOrEmpty(key)) return;
            if (key.ToLower() == "buffersize")
            {
                bufflen = (int)v;
            }
 
        }
        /// <summary>
        /// 取得当前压缩器的执行参数
        /// </summary>
        /// <param name="key">键名</param>
        /// <returns></returns>
        public object GetArguments(string key)
        {
            if (string.IsNullOrEmpty(key)) return null;
            if (key.ToLower() == "buffersize")
                return bufflen;
            return null;
        }
        /// <summary>
        /// 取出最后一次错误
        /// </summary>
        /// <returns></returns>
        public Exception GetLastError()
        {
            return _ex;
        }

        #endregion
    }
}

 

using System;
using System.Collections.Generic;
using System.Text;

namespace LicenseMaintenance
{
    public interface ICompress
    {
        void SetArguments(string key, object v);
        object GetArguments(string key);
        bool CompressSingleFile(string srcpath, string despath);
        bool Compress(string srcpath,string despath);
        bool Compress(string srcpath,string despath , string psw);
        bool UnCompress(string srcpath, string despath);
        bool UnCompress(string srcpath, string despath, string psw);
        Exception GetLastError();
    }
}

使用方法压缩:

View Code
public static bool ZipFile(string filePath, string zipPath)
        {
            //XZip.ZipClass objZip = new XZip.ZipClass();
            ICompress objZip = new CZip();

            try
            {
                //objZip.Pack(filePath, zipPath, false, "", 1);
                objZip.CompressSingleFile(filePath, zipPath);
                System.IO.File.Delete(filePath);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return true;
        }

 

posted on 2012-11-08 11:27  Black Bean  阅读(512)  评论(0编辑  收藏  举报