在.NET可以通过多种方式实现zip的压缩和解压:1、使用System.IO.Packaging;2、使用第三方类库;3、通过 System.IO.Compression 命名空间中新增的ZipArchive、ZipFile等类实现。

     一、使用System.IO.Packaging压缩和解压

     Package为一个抽象类,可用于将对象组织到定义的物理格式的单个实体中,从而实现可移植性与高效访问。ZIP 文件是Package的主物理格式。 其他Package实现可以使用其他物理格式(如 XML 文档、数据库或 Web 服务。与文件系统类似,在分层组织的文件夹和文件中引用 Package 中包含的项。虽然 Package 是抽象类,但 Package.Open 方法默认使用 ZipPackage 派生类。

    System.IO.Packaging在WindowsBase.dll程序集下,使用时需要添加对WindowsBase的引用。

    1、将整个文件夹压缩成zip

        /// <summary>
        /// Add a folder along with its subfolders to a Package
        /// </summary>
        /// <param name="folderName">The folder to add</param>
        /// <param name="compressedFileName">The package to create</param>
        /// <param name="overrideExisting">Override exsisitng files</param>
        /// <returns></returns>
        static bool PackageFolder(string folderName, string compressedFileName, bool overrideExisting)
        {
            if (folderName.EndsWith(@"\"))
                folderName = folderName.Remove(folderName.Length - 1);
            bool result = false;
            if (!Directory.Exists(folderName))
            {
                return result;
            }

            if (!overrideExisting && File.Exists(compressedFileName))
            {
                return result;
            }
            try
            {
                using (Package package = Package.Open(compressedFileName, FileMode.Create))
                {
                    var fileList = Directory.EnumerateFiles(folderName, "*", SearchOption.AllDirectories);
                    foreach (string fileName in fileList)
                    {
                       
                        //The path in the package is all of the subfolders after folderName
                        string pathInPackage;
                        pathInPackage = Path.GetDirectoryName(fileName).Replace(folderName, string.Empty) + "/" + Path.GetFileName(fileName);

                        Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(pathInPackage, UriKind.Relative));
                        PackagePart packagePartDocument = package.CreatePart(partUriDocument,"", CompressionOption.Maximum);
                        using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                        {
                            fileStream.CopyTo(packagePartDocument.GetStream());
                        }
                    }
                }
                result = true;
            }
            catch (Exception e)
            {
                throw new Exception("Error zipping folder " + folderName, e);
            }
           
            return result;
        }
View Code

相关文章:

  • 2022-12-23
  • 2021-12-20
  • 2022-12-23
  • 2021-10-06
  • 2021-09-20
  • 2022-01-19
  • 2021-11-30
  • 2022-12-23
猜你喜欢
  • 2021-09-10
  • 2021-06-26
  • 2022-01-30
  • 2022-12-23
  • 2022-12-23
  • 2022-02-28
相关资源
相似解决方案