File compression and decompression in asp. NET (3 methods) and asp. net3 Methods
In.. NET can be compressed and decompressed in multiple ways: 1. Use System. IO. packaging; 2. Use a third-party class library; 3. Use System. IO. zipArchive, ZipFile, and other class implementations added to the Compression namespace.
1. Use System. IO. Packaging for compression and decompression
A Package is an abstract class used to organize objects into a single object in a defined physical format, so as to realize portability and efficient access. The ZIP file is the main physical format of the Package. Other Package implementations can use other physical formats (such as XML documents, databases, or Web services. Similar to a file system, you can reference items contained in a Package in folders and files of a hierarchical organization. Although Package is an abstract class, the Package. Open method uses the ZipPackage class by default.
System. IO. Packaging is in the WindowsBase. dll assembly. You must add a reference to WindowsBase when using it.
1. compress the entire folder to 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; }
2. Add a single file to a zip file
/// <summary> /// Compress a file into a ZIP archive as the container store /// </summary> /// <param name="fileName">The file to compress</param> /// <param name="compressedFileName">The archive file</param> /// <param name="overrideExisting">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. decompress the zip file
/// <summary> /// Extract a container Zip. NOTE: container must be created as Open Packaging Conventions (OPC) specification /// </summary> /// <param name="folderName">The folder to extract the package to</param> /// <param name="compressedFileName">The package file</param> /// <param name="overrideExisting">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('\\', '/'); 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); } }
When a Package is used to compress a file, [Content_Type]. xml is automatically generated in the zip file to describe the file formats supported by the zip file decompression.
<?xml version="1.0" encoding="utf-8" ?> <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"> <Default Extension="vsixmanifest" ContentType="text/xml" /> <Default Extension="dll" ContentType="application/octet-stream" /> <Default Extension="png" ContentType="application/octet-stream" /> <Default Extension="txt" ContentType="text/plain" /> <Default Extension="pkgdef" ContentType="text/plain" /> </Types>
Similarly, if the zip file does not contain [Content_Type]. xml file, or [Content_Type]. the xml file does not contain the description of the corresponding extension (manually added [Content_Type]. xml is also acceptable). Files cannot be extracted.
Ii. Use third-party class libraries
Zip compression and decompression are compared with SharpZipLib and DotNetZip.
1. SharpZipLib, also known as "# ziplib", is based on GPL open source and supports Zip, GZip, Tar, and BZip2 compression and decompression.
Supports. NET 1.1, NET 2.0 (3.5, 4.0 ).
(1) zip Compression
public static void Zip(string SrcFile, string DstFile, int BufferSize){ FileStream fileStreamIn = new FileStream (SrcFile, FileMode.Open, FileAccess.Read); FileStream fileStreamOut = new FileStream (DstFile, FileMode.Create, FileAccess.Write); ZipOutputStream zipOutStream = new ZipOutputStream(fileStreamOut); byte[] buffer = new byte<buffersize />; ZipEntry entry = new ZipEntry(Path.GetFileName(SrcFile)); zipOutStream.PutNextEntry(entry); int size; do { size = fileStreamIn.Read(buffer, 0, buffer.Length); zipOutStream.Write(buffer, 0, size); } while (size > 0); zipOutStream.Close(); fileStreamOut.Close(); fileStreamIn.Close();}
(2) decompress the zip file
public static void UnZip(string SrcFile, string DstFile, int BufferSize){ FileStream fileStreamIn = new FileStream (SrcFile, FileMode.Open, FileAccess.Read); ZipInputStream zipInStream = new ZipInputStream(fileStreamIn); ZipEntry entry = zipInStream.GetNextEntry(); FileStream fileStreamOut = new FileStream (DstFile + @"\" + entry.Name, FileMode.Create, FileAccess.Write); int size; byte[] buffer = new byte<buffersize />; do { size = zipInStream.Read(buffer, 0, buffer.Length); fileStreamOut.Write(buffer, 0, size); } while (size > 0); zipInStream.Close(); fileStreamOut.Close(); fileStreamIn.Close();}
2, DotNetLib, is based on "WS-PL" open source, relatively simple to use
(1) Compression
using (ZipFile zip = new ZipFile()) { zip.AddFile("ReadMe.txt"); zip.AddFile("7440-N49th.png"); zip.AddFile("2008_Annual_Report.pdf"); zip.Save("Archive.zip"); }
(2) Extract
private void MyExtract() { string zipToUnpack = "C1P3SML.zip"; string unpackDirectory = "Extracted Files"; using (ZipFile zip1 = ZipFile.Read(zipToUnpack)) { // here, we extract every entry, but we could extract conditionally // based on entry name, size, date, checkbox status, etc. foreach (ZipEntry e in zip1) { e.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently); } } }
Iii. Use ZipArchive, ZipFile, and other classes in. NET 4.5 for compression and decompression
static void Main(string[] args) { string ZipPath = @"c:\users\exampleuser\start.zip"; string ExtractPath = @"c:\users\exampleuser\extract"; string NewFile = @"c:\users\exampleuser\NewFile.txt"; using (ZipArchive Archive = ZipFile.Open(ZipPath, ZipArchiveMode.Update)) { Archive.CreateEntryFromFile(NewFile, "NewEntry.txt"); Archive.ExtractToDirectory(ExtractPath); } }
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.