asp.NET中实现文件的压缩和解压(3种方式)

在.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>The folder to add</param> /// <param>The package to create</param> /// <param>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) + "https://www.jb51.net/" + 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; }

2、将单个文件添加到zip文件中

/// <summary> /// Compress a file into a ZIP archive as the container store /// </summary> /// <param>The file to compress</param> /// <param>The archive file</param> /// <param>override existing file</param> /// <returns></returns> static bool PackageFile(string fileName, string compressedFileName, bool overrideExisting) { bool result = false; if (!File.Exists(fileName)) { return result; } if (!overrideExisting && File.Exists(compressedFileName)) { return result; } try { Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(Path.GetFileName(fileName), UriKind.Relative)); using (Package package = Package.Open(compressedFileName, FileMode.OpenOrCreate)) { if (package.PartExists(partUriDocument)) { package.DeletePart(partUriDocument); } 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 file " + fileName, e); } return result; }

3、zip文件解压

/// <summary> /// Extract a container Zip. NOTE: container must be created as Open Packaging Conventions (OPC) specification /// </summary> /// <param>The folder to extract the package to</param> /// <param>The package file</param> /// <param>override existing files</param> /// <returns></returns> static bool UncompressFile(string folderName, string compressedFileName, bool overrideExisting) { bool result = false; try { if (!File.Exists(compressedFileName)) { return result; } DirectoryInfo directoryInfo = new DirectoryInfo(folderName); if (!directoryInfo.Exists) directoryInfo.Create(); using (Package package = Package.Open(compressedFileName, FileMode.Open, FileAccess.Read)) { foreach (PackagePart packagePart in package.GetParts()) { ExtractPart(packagePart, folderName, overrideExisting); } } result = true; } catch (Exception e) { throw new Exception("Error unzipping file " + compressedFileName, e); } return result; } static void ExtractPart(PackagePart packagePart, string targetDirectory, bool overrideExisting) { string stringPart = targetDirectory + HttpUtility.UrlDecode(packagePart.Uri.ToString()).Replace('\\', 'https://www.jb51.net/'); if (!Directory.Exists(Path.GetDirectoryName(stringPart))) Directory.CreateDirectory(Path.GetDirectoryName(stringPart)); if (!overrideExisting && File.Exists(stringPart)) return; using (FileStream fileStream = new FileStream(stringPart, FileMode.Create)) { packagePart.GetStream().CopyTo(fileStream); } }

使用Package压缩文件会在zip文件自动生成[Content_Type].xml,用来描述zip文件解压支持的文件格式。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjyzfs.html