Asp. NET in the implementation of file compression and decompression (3 ways) _ Practical skills

Source: Internet
Author: User
Tags abstract getstream int size ziparchive

In. NET, zip compression and decompression can be implemented in a variety of ways: 1, using SYSTEM.IO.PACKAGING;2, using a Third-party class library, 3, the new ziparchive through the System.IO.Compression namespace, ZipFile and other class implementations.

First, using System.IO.Packaging compression and decompression

Package is an abstract class that can be used to organize objects into a single entity in a defined physical format, enabling portability and efficient access. The ZIP file is the package primary physical format. Other package implementations can use other physical formats, such as XML documents, databases, or WEB services. Similar to file systems, the items contained in Package are referenced in folders and files in a hierarchical organization. Although Package is an abstract class, the Package.Open method uses ZipPackage derived classes by default.

System.IO.Packaging The WindowsBase.dll assembly, you need to add a reference to WindowsBase when you use it.

1, the entire folder compressed into a zip

 <summary>///Add a folder along with it subfolders to a Package///</summary>///<param Nam E= "FolderName" >the folder to add</param>///<param name= "Compressedfilename" >the package to create</ param>///<param name= "overrideexisting" >override exsisitng files</param>///, <returns></ret urns> static bool Packagefolder (string folderName, String compressedfilename, bool overrideexisting) {if (Folde
   Rname.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 = Di Rectory.
     Enumeratefiles (FolderName, "*", searchoption.alldirectories);
   foreach (String fileName in FileList) {   
      The path in the package are 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, adding a single file to the zip file

 <summary>///Compress a file into a ZIP archive as the Container store///</summary>///<par Am Name= "fileName" >the file to compress</param>///<param name= "Compressedfilename" >the Archive ;/param>///<param name= "overrideexisting" >override existing file</param>///, <returns></ret  urns> 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 (PA
     Ckagepartdocument.getstream ());
   result = true;
   catch (Exception e) {throw new Exception ("Error zipping file" + FileName, E);
  return result;

 }

3, zip file decompression

<summary>///Extract a container Zip. Note:container must be created as Open Packaging Conventions (OPC) specification///</summary>///<param N Ame= "FolderName" >the folder to extract the package to</param>///<param name= "Compressedfilename" >the PA Ckage file</param>///<param name= "overrideexisting" >override existing files</param>///, <return
  s></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 STRINGP Art = 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);

 }
  }

Using the package compressed file is automatically generated in the zip file [content_type].xml to describe the file format 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 a [Content_type].xml file, or the [Content_type].xml file does not contain a description of the corresponding extension (manually added [Content_type].xml is also possible), the file cannot be uncompressed.

Second, use the Third party class library

The compression and decompression of zip are compared with sharpziplib and DotNetZip.

1, SharpZipLib, also known as "#ziplib", based on the GPL open source, support 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< c3/> (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) Extract zip

  public static void UnZip (String srcfile, string dstfile, int buffersize)
{
 FileStream filestreamin = new Filestrea M
 (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, the use of relatively simple

(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) Decompression

 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 Onally
   //Based on entry name, size, date, checkbox status, etc. 
   foreach (ZipEntry e in zip1)
   {
   e.extract (unpackdirectory, extractexistingfileaction.overwritesilently);
   }
  }
 }

Third, in. NET 4.5 use ziparchive, ZipFile and other classes of 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 the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.