在要求输入邮箱的文本域,请填写真实的邮件地址。非真实邮件地址,将收不到回复信息。

C#利用ICSharpCode.SharpZipLib.dll实现对文件的压缩与解压

C# 清风 418℃ 0评论

因为程序中需要对指定文件进行压缩,然后再对已压缩的文件进行加密上传,所以,在网上找了一个已经实现的方法就用了。结果不用不知道,用了就差点挂掉,网上找到的类中解压会出问题,竟然能多出很多数据,压缩多级目录竟然出现目录错乱等诸多问题。最终,对出现的问题也进行了相关的修改(未发现的问题就不晓得了),利用C#的开源组件ICSharpCode.SharpZipLib实现,以下对代码就做下记录。


    public static class ZipUtil
    {

        #region 压缩

        /// <summary>   
        /// 递归压缩文件夹的内部方法   
        /// </summary>    
        /// <param name="folderToZip">要压缩的文件夹路径</param>    
        /// <param name="zipStream">压缩输出流</param>    
        /// <param name="parentFolderName">此文件夹的上级文件夹</param>    
        ///    
        private static bool ZipDirectory(string folderToZip, ZipOutputStream zipStream, string parentFolderName)
        {
            bool result = true;
            string[] folders, files;
            ZipEntry ent = null;
            FileStream fs = null;
            Crc32 crc = new Crc32();
            try
            {
                folders = Directory.GetDirectories(folderToZip);
                foreach (string folder in folders)
                {
                    if (!ZipDirectory(folder, zipStream, folderToZip))
                    {
                        return false;
                    }
                }
                files = Directory.GetFiles(folderToZip);
                foreach (string file in files)
                {
                    fs = File.OpenRead(file);
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    string filePath = "";
                    if (string.IsNullOrEmpty(parentFolderName))
                    {
                        filePath = file.Substring(folderToZip.LastIndexOf("\\") + 1);
                    }
                    else
                    {
                        filePath = file.Substring(parentFolderName.LastIndexOf("\\") + 1);
                    }
                    ent = new ZipEntry(filePath);
                    ent.DateTime = DateTime.Now;
                    ent.Size = fs.Length;
                    fs.Close();
                    crc.Reset();
                    crc.Update(buffer);
                    ent.Crc = crc.Value;
                    zipStream.PutNextEntry(ent);
                    zipStream.Write(buffer, 0, buffer.Length);
                }

            }
            catch
            {
                result = false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                if (ent != null)
                {
                    ent = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
            return result;
        }

        /// <summary>   
        /// 压缩文件夹    
        /// </summary>    
        /// <param name="folderToZip">要压缩的文件夹路径</param>    
        /// <param name="zipedFile">压缩文件完整路径</param>    
        /// <param name="password">密码</param>    
        /// 是否压缩成功   
        public static bool ZipDirectory(string folderToZip, string zipedFile, string password)
        {
            bool result = false;
            if (!Directory.Exists(folderToZip))
            {
                return result;
            }
            ZipOutputStream zipStream = new ZipOutputStream(File.Create(zipedFile));
            zipStream.SetLevel(6);
            if (!string.IsNullOrEmpty(password))
            {
                zipStream.Password = password;
            }
            result = ZipDirectory(folderToZip, zipStream, "");
            zipStream.Finish();
            zipStream.Close();
            return result;
        }

        /// <summary>   
        /// 压缩文件夹   
        /// </summary>    
        /// <param name="folderToZip">要压缩的文件夹路径</param>    
        /// <param name="zipedFile">压缩文件完整路径</param>    
        /// 是否压缩成功   
        public static bool ZipDirectory(string folderToZip, string zipedFile)
        {
            bool result = ZipDirectory(folderToZip, zipedFile, null);
            return result;
        }

        /// <summary>   
        /// 压缩文件   
        /// </summary>    
        /// <param name="fileToZip">要压缩的文件全名</param>    
        /// <param name="zipedFile">压缩后的文件名</param>    
        /// <param name="password">密码</param>    
        /// 压缩结果   
        public static bool ZipFile(string fileToZip, string zipedFile, string password)
        {
            bool result = true;
            ZipOutputStream zipStream = null;
            FileStream fs = null;
            ZipEntry ent = null;

            if (!File.Exists(fileToZip))
                return false;

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

                fs = File.Create(zipedFile);
                zipStream = new ZipOutputStream(fs);
                if (!string.IsNullOrEmpty(password)) zipStream.Password = password;
                ent = new ZipEntry(Path.GetFileName(fileToZip));
                zipStream.PutNextEntry(ent);
                zipStream.SetLevel(6);

                zipStream.Write(buffer, 0, buffer.Length);

            }
            catch
            {
                result = false;
            }
            finally
            {
                if (zipStream != null)
                {
                    zipStream.Finish();
                    zipStream.Close();
                }
                if (ent != null)
                {
                    ent = null;
                }
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                if (!result && !string.IsNullOrEmpty(zipedFile) && File.Exists(zipedFile))
                {
                    File.Delete(zipedFile);
                }
            }
            GC.Collect();
            GC.Collect(1);

            return result;
        }

        /// <summary>
        /// 压缩文件 将指定的文件列表压缩为一个文件压缩包
        /// </summary> 
        /// <param name="fileToZipList">需要压缩的文件列表</param> 
        /// <param name="zipedFile">将要压缩为ZIP的文件</param> 
        /// <param name="password">压缩包密码。可以为空</param> 
        /// 
        public static bool ZipFile(List fileToZipList, string zipedFile, string password = "")
        {
            bool result = false;
            foreach (string item in fileToZipList)
            {
                if (!File.Exists(item))
                {
                    return result;
                }
            }
            ZipOutputStream zipStream = new ZipOutputStream(File.Create(zipedFile));
            zipStream.SetLevel(6);
            if (!string.IsNullOrEmpty(password))
            {
                zipStream.Password = password;
            }
            ZipEntry ent = null;
            FileStream fs = null;
            Crc32 crc = new Crc32();
            try
            {
                foreach (string file in fileToZipList)
                {
                    fs = File.OpenRead(file);
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    string filePath = Path.GetFileName(file);
                    ent = new ZipEntry(filePath);
                    ent.DateTime = DateTime.Now;
                    ent.Size = fs.Length;
                    fs.Close();
                    crc.Reset();
                    crc.Update(buffer);
                    ent.Crc = crc.Value;
                    zipStream.PutNextEntry(ent);
                    zipStream.Write(buffer, 0, buffer.Length);
                }
                result = true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                if (ent != null)
                {
                    ent = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
            zipStream.Finish();
            zipStream.Close();
            return result;
        }

        /// <summary>   
        /// 压缩文件   
        /// </summary>    
        /// <param name="fileToZip">要压缩的文件全名</param>    
        /// <param name="zipedFile">压缩后的文件名</param>    
        /// 压缩结果   
        public static bool ZipFile(string fileToZip, string zipedFile)
        {
            bool result = ZipFile(fileToZip, zipedFile, null);
            return result;
        }

        /// <summary>   
        /// 压缩文件或文件夹   
        /// </summary>    
        /// <param name="fileToZip">要压缩的路径</param>    
        /// <param name="zipedFile">压缩后的文件名</param>    
        /// <param name="password">密码</param>    
        /// 压缩结果   
        public static bool Zip(string fileToZip, string zipedFile, string password)
        {
            bool result = false;
            if (Directory.Exists(fileToZip))
                result = ZipDirectory(fileToZip, zipedFile, password);
            else if (File.Exists(fileToZip))
                result = ZipFile(fileToZip, zipedFile, password);

            return result;
        }

        /// <summary>   
        /// 压缩文件或文件夹   
        /// </summary>    
        /// <param name="fileToZip">要压缩的路径</param>    
        /// <param name="zipedFile">压缩后的文件名</param>    
        /// 压缩结果   
        public static bool Zip(string fileToZip, string zipedFile)
        {
            bool result = Zip(fileToZip, zipedFile, null);
            return result;

        }

        #endregion

        #region 解压

        /// <summary>   
        /// 解压功能(解压压缩文件到指定目录)   
        /// </summary>    
        /// <param name="fileToUnZip">待解压的文件</param>    
        /// <param name="zipedFolder">指定解压目标目录</param>    
        /// <param name="password">密码</param>    
        /// 解压结果   
        public static bool UnZip(string fileToUnZip, string zipedFolder, string password)
        {
            bool result = true;
            FileStream fs = null;
            ZipInputStream zipStream = null;
            ZipEntry ent = null;
            FileStream fileStream = null;
            string fileName = "";

            if (!File.Exists(fileToUnZip))
                return false;

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

            try
            {
                fileStream = File.OpenRead(fileToUnZip);
                zipStream = new ZipInputStream(fileStream);
                if (!string.IsNullOrEmpty(password)) { zipStream.Password = password; }
                while ((ent = zipStream.GetNextEntry()) != null)
                {
                    if (!string.IsNullOrEmpty(ent.Name))
                    {
                        fileName = Path.Combine(zipedFolder, ent.Name);
                        fileName = fileName.Replace('/', '\\');//change by Mr.HopeGi   

                        int index = ent.Name.LastIndexOf('/');
                        if (index != -1 || fileName.EndsWith("\\"))
                        {
                            string tmpDir = (index != -1 ? fileName.Substring(0, fileName.LastIndexOf('\\')) : fileName) + "\\";
                            if (!Directory.Exists(tmpDir))
                            {
                                Directory.CreateDirectory(tmpDir);
                            }
                            if (tmpDir == fileName)
                            {
                                continue;
                            }
                        }

                        fs = File.Create(fileName);

                        int size = 2048;
                        byte[] data = new byte[size];
                        while (true)
                        {
                            size = zipStream.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                fs.Write(data, 0, size);
                                Array.Clear(data, 0, data.Length);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                if (zipStream != null)
                {
                    zipStream.Close();
                    zipStream.Dispose();
                }
                if (ent != null)
                {
                    ent = null;
                }
                fileStream?.Close();
                fileStream?.Dispose();
                GC.Collect();
                GC.Collect(1);
                if (!result)
                {
                    if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName))
                    {
                        File.Delete(fileName);
                    }
                }
            }
            return result;
        }

        /// <summary>   
        /// 解压功能(解压压缩文件到指定目录)   
        /// </summary>    
        /// <param name="fileToUnZip">待解压的文件</param>    
        /// <param name="zipedFolder">指定解压目标目录</param>    
        /// 解压结果   
        public static bool UnZip(string fileToUnZip, string zipedFolder)
        {
            bool result = UnZip(fileToUnZip, zipedFolder, null);
            return result;
        }
        #endregion

    }

 

 

 

 

 

 

转载请注明:清风博客 » C#利用ICSharpCode.SharpZipLib.dll实现对文件的压缩与解压

喜欢 (0)or分享 (0)
支付宝扫码打赏 微信打赏
发表我的评论
取消评论

CAPTCHA Image
Reload Image
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址