• 本站域名:OceanCoder.cn 若您喜欢本站,请添加至收藏夹!
  • 网站少部分资源来源自网络,如有侵犯您的权益,请联系站长删除!
  • 本站所有文章,除特殊标明外,皆为本人原创,转载请注明出处,谢谢合作!
  • 本站所下载的资源,若无特殊说明,使用统一解压密码:oceancoder.cn
  • 本站已实现布局自适应,支持手机端、pad端访问,欢迎体验
  • 本站部分资源可通过微信公众号留言获取,欢迎体验

[C#]利用ICSharpCode.SharpZipLib实现加密码压缩与解压缩

C# OceanCoder 2017-07-22 3619 次浏览 0个评论

相关的ICSharpCode.SharpZipLib的DLL可以到这里下载:http://icsharpcode.github.io/SharpZipLib/

/// <summary>
        /// 文件加密压缩
        /// </summary>
        /// <param name="FileToZip">需要压缩的文件路径</param>
        /// <param name="ZipedFile">压缩包路径(压缩包文件类型看自己需求)</param>
        /// <param name="password">加密密码</param>
        public void ZipFileMain(string FileToZip, string ZipedFile, string password)
        {
            ZipOutputStream s = new ZipOutputStream(File.Create(ZipedFile));
            s.SetLevel(6); // 0 - store only to 9 - means best compression
            s.Password = password;
            //打开压缩文件 
            FileStream fs = File.OpenRead(FileToZip);
            byte[] buffer = new byte[fs.Length];
            fs.Read(buffer, 0, buffer.Length);
            Array arr = FileToZip.Split('\\');
            string le = arr.GetValue(arr.Length - 1).ToString();
            ZipEntry entry = new ZipEntry(le);
            entry.DateTime = DateTime.Now;
            entry.Size = fs.Length;
            fs.Close();
            s.PutNextEntry(entry);
            s.Write(buffer, 0, buffer.Length);
            s.Finish();
            s.Close();
        }
        
        //解压缩
        public void UnZip(string directoryName, string ZipedFile, string password)
        {
            using (FileStream fileStreamIn = new FileStream(ZipedFile, FileMode.Open, FileAccess.Read))
            {
                using (ZipInputStream zipInStream = new ZipInputStream(fileStreamIn))
                {
                    zipInStream.Password = password;
                    ZipEntry entry = zipInStream.GetNextEntry();
                    //WebContext.SqlfilePath = directoryName + "\\" + entry.Name;
                    do
                    {
                        using (FileStream fileStreamOut = new FileStream(directoryName + @"\" + entry.Name, FileMode.Create, FileAccess.Write))
                        {
                            int size = 2048;
                            byte[] buffer = new byte[2048];
                            do
                            {
                                size = zipInStream.Read(buffer, 0, buffer.Length);
                                fileStreamOut.Write(buffer, 0, size);
                            } while (size > 0);
                        }
                    } while ((entry = zipInStream.GetNextEntry()) != null);
                }
            }
        }

建议密码使用英文!


已有 3619 位网友参与,快来吐槽:

发表评论