C# 压缩、解压缩文件

用了 Log4net 记录日志,如果没有 Log4net 的,将 Log4net  注释即可运行

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Collections;
using System.IO;
using ICSharpCode.SharpZipLib.Zip; 
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip.Compression;
using log4net;


namespace FiSMDataClient.Service
{
    public class ZipLib
    {
        private static readonly ILog LOG = LogManager.GetLogger(typeof(FileLib));
        public ArrayList fileList = new ArrayList();
        string changname=null;
       
        #region 压缩文件
        /// <summary>
        /// 压缩多文件(调用之前先为fileList 赋值)
        /// </summary>
        /// <param name="outZipPath">输出Zip文件的全路径</param>
        public void Compress(string outZipPath)
        {
            try
            {
                Crc32 crc = new Crc32();
                ZipOutputStream zipStream = new ZipOutputStream(File.Create(outZipPath));
                zipStream.SetLevel(9); // 0 - store only to 9 - means best compression
                foreach (string file in FileList)
                {
                    FileStream fStream = File.OpenRead(file);
                    byte[] buffer = new byte[fStream.Length];
                    fStream.Read(buffer, 0, buffer.Length);
                    string filename = file.Substring(file.LastIndexOf("//") + 1, file.Length - file.LastIndexOf("//") - 1);
                    ZipEntry entry = new ZipEntry(filename);
                    entry.DateTime = DateTime.Now;
                    entry.Size = fStream.Length;
                    fStream.Close();
                    crc.Reset();
                    crc.Update(buffer);
                    entry.Crc = crc.Value;
                    zipStream.PutNextEntry(entry);
                    zipStream.Write(buffer, 0, buffer.Length);
                }
                zipStream.Finish();
                zipStream.Close();
            }
            catch
            {
            }
        }
        #endregion

        #region 解压缩文件
        /// <summary>
        /// 解压缩文件
        /// </summary>
        /// <param name="srcPath">待解压文件全路径</param>
        /// <param name="outPutPath">解压后的文件路径</param>
        /// <param name="outPutOldPath">解压后的文件路径</param>
        public bool UnCompress(string srcPath, string outPutPath, string outPutOldPath)
        {

            try
            {
                ZipInputStream s = new ZipInputStream(File.OpenRead(srcPath));
                string realPath = Path.GetDirectoryName(srcPath);
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {

                    outPutPath = Path.GetDirectoryName(outPutOldPath + "//" + theEntry.Name);

                    string fileName = Path.GetFileName(theEntry.Name);

                    Directory.CreateDirectory(outPutPath);
                    if (fileName != String.Empty)
                    {

                        FileStream streamWriter = File.Create(outPutOldPath + "//" + theEntry.Name);
                        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
                            {
                                break;
                            }
                        }

                        streamWriter.Close();
                        if (fileName.ToLower().EndsWith(".zip"))
                        {
                            UnCompress(realPath + @"/" + fileName, outPutPath, outPutOldPath);
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                LOG.Error("ZipLib类UnCompress()异常:"+ex.Message);
                return false;
            }
            return true;
        }
        public bool UnCompressExcel(string srcPath, string outPutPath, string outPutOldPath)
        {

            try
            {
                ZipInputStream s = new ZipInputStream(File.OpenRead(srcPath));
                string realPath = Path.GetDirectoryName(srcPath);
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    
                    outPutPath = Path.GetDirectoryName(outPutOldPath + "//" + theEntry.Name);

                    string fileName = Path.GetFileName(theEntry.Name);
                    
                    //Directory.CreateDirectory(outPutPath);
                    if (fileName != String.Empty)
                    {
                        string relfilename = System.Web.HttpUtility.UrlDecode(fileName);
                        string rootpath = outPutOldPath;
                        if (!Directory.Exists(rootpath))
                        {
                            Directory.CreateDirectory(rootpath);
                        }
                        if (relfilename.Contains("@"))
                        {
                            string[] splitfilenames = relfilename.Split(new string[] { "@" }, new StringSplitOptions());
                            fileName = splitfilenames[splitfilenames.Length - 1];
                            for (int number = 0; number < splitfilenames.Length - 1; number++)
                            {
                                
                                    rootpath += "//" + splitfilenames[number]+"######";
                                    if (!Directory.Exists(rootpath))
                                    {
                                        Directory.CreateDirectory(rootpath);
                                    }
                              
                            }


                        }

 

                        CheckAndChangFilename(fileName, rootpath);
                       FileStream streamWriter = File.Create(rootpath + "//" + fileName);                     
                        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
                            {
                                break;
                            }
                        }

                        streamWriter.Close();
                        if (fileName.ToLower().EndsWith(".zip"))
                        {
                            UnCompress(realPath + @"/" + fileName, outPutPath, outPutOldPath);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LOG.Error("ZipLib类UnCompress()异常:" + ex.Message);
                return false;
            }
            return true;
        }

        private void  CheckAndChangFilename(string fileName, string rootpath)       //判断如果有重名则更换名字
        {
           
              if (fileName.Contains(".xls"))
             {
                 string[] splitnames = fileName.Split(new string[] { ".xls" }, new StringSplitOptions());
                 int flag = CheckTheSameFile(rootpath, splitnames[0]);
                  if (flag > 0)
                 {      
                    changname = splitnames[0] + flag.ToString();               
                    System.IO.File.Copy(rootpath + "//" + fileName, rootpath + "//" + changname + ".xls", true);
                    File.Delete(rootpath + "//" + fileName);
                   
                }

            }
         
        }
        #endregion
        public int CheckTheSameFile(string rootpath,string filename)
        {
            int flag = 0;
            string[] files = Directory.GetFiles(rootpath);
            foreach(string file in files)
            {   
                string filena = Path.GetFileName(file);
                if (filena.Contains(".xls"))
                {
                    string[] splitfilena = filena.Split(new string[] { ".xls" }, new StringSplitOptions());
                    if (splitfilena[0].Contains(filename))
                    {
                        flag++;
                    }
                }
            }

            return flag;
        }

        #region 属性
        /// <summary>
        /// 待压缩文件的全路径名
        /// </summary>
        public ArrayList FileList
        {
            get { return fileList; }
            set { fileList = value; }
        }

        #endregion

    }

}
 
原文地址:https://www.cnblogs.com/iwenwen/p/3133532.html