文件压缩

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

namespace NEEA.CET.Common
{
  public  class ZipManager
    {
        #region 压缩
        /// 
        /// 压缩文件,默认目录为当前目录,文件名为当前目录名,压缩级别为6
        /// 
        /// 要压缩的文件或文件夹
        public void Zip(params string[] fileOrDirectory)
        {
            Zip(6, fileOrDirectory);
        }

        /// 
        /// 压缩文件,默认目录为当前目录,文件名为当前目录名
        /// 
        /// 压缩的级别
        /// 要压缩的文件或文件夹
        public void Zip(int zipLevel, params string[] fileOrDirectory)
        {
            if (fileOrDirectory == null)
                return;
            else if (fileOrDirectory.Length < 1)
                return;
            else
            {
                string str = fileOrDirectory[0];
                if (str.EndsWith("\\"))
                    str = str.Substring(0, str.Length - 1);
                str += ".zip";
                Zip(str, zipLevel, fileOrDirectory);
            }
        }
        /// 
        /// 压缩文件,默认目录为当前目录
        /// 
        /// 压缩后的文件
        /// 压缩的级别
        /// 要压缩的文件或文件夹
        public void ZipUsePassword(string zipedFileName, int zipLevel, string passWord, params string[] fileOrDirectory)
        {
            if (fileOrDirectory == null)
                return;
            else if (fileOrDirectory.Length < 1)
                return;
            else
            {
                string str = fileOrDirectory[0];
                if (str.EndsWith("\\"))
                    str = str.Substring(0, str.Length - 1);
                str = str.Substring(0, str.LastIndexOf("\\"));
                Zip(zipedFileName, str, zipLevel, passWord, fileOrDirectory);
            }
        }
        public void Zip(string zipedFileName, string currentDirectory, int zipLevel, string passWord, params string[] fileOrDirectory)
        {
            ArrayList AllFiles = new ArrayList();

            //获取所有文件
            if (fileOrDirectory != null)
            {
                for (int i = 0; i < fileOrDirectory.Length; i++)
                {
                    if (File.Exists(fileOrDirectory[i]))
                        AllFiles.Add(fileOrDirectory[i]);
                    else if (Directory.Exists(fileOrDirectory[i]))
                        GetDirectoryFile(fileOrDirectory[i], AllFiles);
                }
            }

            if (AllFiles.Count < 1)
                return;

            ZipOutputStream zipedStream = new ZipOutputStream(File.Create(zipedFileName));
            zipedStream.SetLevel(zipLevel);
            if (!string.IsNullOrEmpty(passWord))
            {
                zipedStream.Password = passWord;
            }

            for (int i = 0; i < AllFiles.Count; i++)
            {
                string file = AllFiles[i].ToString();
                FileStream fs;

                //打开要压缩的文件
                //try
                //{
                fs = File.OpenRead(file);
                //}
                //catch
                //{
                //    continue;
                //}

                try
                {
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);

                    //新建一个entry
                    string fileName = file.Replace(currentDirectory, "");
                    if (fileName.StartsWith("\\"))
                        fileName = fileName.Substring(1);
                    ZipEntry entry = new ZipEntry(fileName.Replace(@"\", @"/"));
                    entry.DateTime = DateTime.Now;

                    //保存到zip流
                    fs.Close();
                    zipedStream.PutNextEntry(entry);
                    zipedStream.Write(buffer, 0, buffer.Length);
                }
                //catch
                //{
                //}
                finally
                {
                    fs.Close();
                    fs.Dispose();
                }
            }

            zipedStream.Finish();
            zipedStream.Close();
        }
        /// 
        /// 压缩文件,默认目录为当前目录
        /// 
        /// 压缩后的文件
        /// 压缩的级别
        /// 要压缩的文件或文件夹
        public void Zip(string zipedFileName, int zipLevel, params string[] fileOrDirectory)
        {
            if (fileOrDirectory == null)
                return;
            else if (fileOrDirectory.Length < 1)
                return;
            else
            {
                string str = fileOrDirectory[0];
                if (str.EndsWith("\\"))
                    str = str.Substring(0, str.Length - 1);
                str = str.Substring(0, str.LastIndexOf("\\"));
                Zip(zipedFileName, str, zipLevel, fileOrDirectory);
            }
        }

        /// 
        /// 压缩文件
        /// 
        /// 压缩后的文件
        /// 压缩的级别
        /// 当前所处目录
        /// 要压缩的文件或文件夹
        public void Zip(string zipedFileName, string currentDirectory, int zipLevel, params string[] fileOrDirectory)
        {
            ArrayList AllFiles = new ArrayList();

            //获取所有文件
            if (fileOrDirectory != null)
            {
                for (int i = 0; i < fileOrDirectory.Length; i++)
                {
                    if (File.Exists(fileOrDirectory[i]))
                        AllFiles.Add(fileOrDirectory[i]);
                    else if (Directory.Exists(fileOrDirectory[i]))
                        GetDirectoryFile(fileOrDirectory[i], AllFiles);
                }
            }

            if (AllFiles.Count < 1)
                return;

            ZipOutputStream zipedStream = new ZipOutputStream(File.Create(zipedFileName));
            zipedStream.SetLevel(zipLevel);

            for (int i = 0; i < AllFiles.Count; i++)
            {
                string file = AllFiles[i].ToString();
                FileStream fs;

                //打开要压缩的文件
                //try
                //{
                fs = File.OpenRead(file);
                //}
                //catch
                //{
                //    continue;
                //}

                try
                {
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);

                    //新建一个entry
                    string fileName = file.Replace(currentDirectory, "");
                    if (fileName.StartsWith("\\"))
                        fileName = fileName.Substring(1);
                    ZipEntry entry = new ZipEntry(fileName.Replace(@"\", @"/"));
                    entry.DateTime = DateTime.Now;

                    //保存到zip流
                    fs.Close();
                    zipedStream.PutNextEntry(entry);
                    zipedStream.Write(buffer, 0, buffer.Length);
                }
                //catch
                //{
                //}
                finally
                {
                    fs.Close();
                    fs.Dispose();
                }
            }

            zipedStream.Finish();
            zipedStream.Close();
        }


        /// 
        /// 压缩文件夹
        /// 
        /// 当前所在的文件夹
        public void ZipDirectory(string curretnDirectory)
        {
            if (curretnDirectory == null)
                return;

            string dir = curretnDirectory;
            if (dir.EndsWith("\\"))
                dir = dir.Substring(0, dir.Length - 1);
            string file = dir.Substring(dir.LastIndexOf("\\") + 1) + ".zip";
            dir += "\\" + file;

            Zip(dir, 6, curretnDirectory);
        }


        /// 
        /// 压缩文件夹
        /// 
        /// 当前所在的文件夹
        public void ZipDirectory(string curretnDirectory, int zipLevel)
        {
            if (curretnDirectory == null)
                return;

            string dir = curretnDirectory;
            if (dir.EndsWith("\\"))
                dir = dir.Substring(0, dir.Length - 1);
            dir += ".zip";

            Zip(dir, zipLevel, curretnDirectory);
        }


        //递归获取一个目录下的所有文件
        private void GetDirectoryFile(string parentDirectory, ArrayList toStore)
        {
            string[] files = Directory.GetFiles(parentDirectory);
            for (int i = 0; i < files.Length; i++)
                toStore.Add(files[i]);
            string[] directorys = Directory.GetDirectories(parentDirectory);
            for (int i = 0; i < directorys.Length; i++)
                GetDirectoryFile(directorys[i], toStore);
        }

        //计算文件大小
        public static string CountSize(long Size)
        {
            string m_strSize = "";
            long FactSize = 0;
            FactSize = Size;
            if (FactSize < 1024.00)
                m_strSize = FactSize.ToString("F2") + " Byte";
            else if (FactSize >= 1024.00 && FactSize < 1048576)
                m_strSize = (FactSize / 1024.00).ToString("F2") + " K";
            else if (FactSize >= 1048576 && FactSize < 1073741824)
                m_strSize = (FactSize / 1024.00 / 1024.00).ToString("F2") + " M";
            else if (FactSize >= 1073741824)
                m_strSize = (FactSize / 1024.00 / 1024.00 / 1024.00).ToString("F2") + " G";
            return m_strSize;
        }
        #endregion

        #region 解压
        /// <summary>
        /// 解压文件
        /// </summary>
        /// <param name="ZipPath">被解压的文件路径</param>
        /// <param name="Path">解压后文件的路径</param>
        public void UnZip(string ZipPath, string Path)
        {
            ZipInputStream s = new ZipInputStream(File.OpenRead(ZipPath));

            ZipEntry theEntry;
            try
            {
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    string fileName = System.IO.Path.GetFileName(theEntry.Name);

                    //生成解压目录
                    string folderName = System.IO.Path.GetDirectoryName(theEntry.Name);
                    if (!Directory.Exists(Path + folderName))
                    {
                        Directory.CreateDirectory(Path + folderName);
                    }

                    if (!string.IsNullOrEmpty(fileName))
                    {
                        //解压文件
                        FileStream streamWriter = File.Create(Path + theEntry);

                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                            else
                            {

                                streamWriter.Close();
                                streamWriter.Dispose();
                                break;
                            }
                        }

                        streamWriter.Close();
                        streamWriter.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                ex._Log();
                throw;
            }
            finally
            {
                s.Close();
                s.Dispose();
            }
        }

        #endregion
    }
}

 

posted @ 2018-08-10 16:58  一直乱跑的熊  阅读(171)  评论(0编辑  收藏  举报