. NET (C #) Create and read instances of Zip compressed documents

Source: Internet
Author: User
Tags extract zip file file size zip ziparchive

To operate on a ZIP file, the following three classes are used primarily:





1, ZipFile. Represents a class associated with a zip file operation. You can use this class to create a zip file or to open a zip file.





2, Ziparchive. Represents a Zip document instance through which you can create a zip document directly from a Stream object. The ZipFile class operates primarily on disk files, while ziparchive represents a zip package, not necessarily a. zip file that is stored on the hard disk, because it can be created based on a stream, so it can be in memory or used for network transmission.





3, Ziparchiveentry. Document item entity. Represents a file entity in a ZIP compression package. A file is an entity in a zip document, and if the directory structure exists, the file entity is described with a relative path, rooted in the current document. For example: \ Directory 1\ directory 2\ file 1.





First look at how to create a new. zip file from an existing directory that contains all of the contents of the directory. The ZipFile class exposes the Createfromdirectory method, which has several overloads that simply create a. zip file if you do not consider other factors, and you can use the following overloads:





static void Createfromdirectory (String sourcedirectoryname, String destinationarchivefilename)





method does not return the content, the Sourcedirectoryname parameter specifies the source directory to use to create the compressed document, Destinationarchivefilename is the full path to the newly created compressed file, such as C:\abc.zip.





If you want to control the compression level, you can use the following overloads:





void Createfromdirectory (String sourcedirectoryname, String destinationarchivefilename, System.IO.Compression.CompressionLevel CompressionLevel, BOOL includebasedirectory)





The CompressionLevel parameter represents the level of compression, and the Includebasedirectory parameter indicates whether the directory name in Sourcedirectoryname is also placed in the root of the. zip file, or False if it is true.








Take a look at the example:





Try
{
zipfile.createfromdirectory (TextBox1.Text, TextBox2.Text);
msg = "Operation succeeded. ";
}
catch (Exception ex)
{
msg = ex. message;
}
MessageBox.Show (MSG, "hint", MessageBoxButtons.OK);


is not very simple.

========================================================

Let's see how to decompress. As opposed to creating a compressed file, the ZipFile class also exposes the Extracttodirectory method, which is used to extract the contents of the specified. zip file into the specified directory. One of the simpler overloads is the following:

static void Extracttodirectory (String sourcearchivefilename, String destinationdirectoryname)

The Sourcearchivefilename parameter specifies the full path or relative path of the zip file to extract, the Destinationdirectoryname parameter specifies a directory, and the pressed content is placed in the directory.

Take a look at the example:

Try
{
zipfile.extracttodirectory (txtzipfile.text, txtdestdir.text);
msg = "Decompression succeeded." ";
}
catch (Exception ex)
{
msg = ex. message;
}
MessageBox.Show (MSG, "hint", MessageBoxButtons.OK);


should place the code in the TRY statement block when it is manipulated, and it is difficult to guarantee that no surprises occur.

 
======================================================

Finally, let's look at how to scan the list of files in the. zip file. The ZipFile class has two methods: if you only consider read-only processing of the. zip file, call the OpenRead method. Call the Open method if you want to process the file in addition to read-only.

Regardless of which method you call, a ziparchive instance is returned that represents a zip document that we can access or modify in code. The Ziparchive object has a entries attribute that represents the list of files contained in the zip file, and the type only treats the file in the compressed package as an entity and the directory is not processed as an entity. This property can return a read-only list of ziparchiveentry instances, and each Ziparchiveentry object in the list represents a file in the compressed package. The

Ziparchiveentry class has several properties to get file information.

 name: filename, does not contain a relative path.

FullName: Contains a relative path and file name.

Length: File size before compression.

Compressedlength: File size after compression.


See the following example:

Try
{
//Open zip file
ziparchive archive = zipfile.openread (txtinputfile.text);
Get file list
var files = archive.    Entries;
Display list
lbfiles.itemssource = files;
msg = "Read succeeded. ";
}
catch (Exception ex)
{
msg = ex. message;
}


The above code reads a. zip file and lists the file objects in the document. The results are shown in the following figure.


In addition, the Ziparchiveentry class also defines a extracttofile extension method that you can use to extract a file from a compressed package.


C # uses the DotNetZip encapsulated class operation zip file (Create/read/update) instance

DotNetZip is an open source class library, supported. NET, you can easily create, read, and update zip files. And it can also be used in. The Netcompact framework. The

Download address is here: http://dotnetzip.codeplex.com/

There are a number of DLL files in the package to download, and general reference Ionic.Zip.dll can:

and then reference this namespace:

using Ionic.zip;

The following is a class that I encapsulate myself:

 <summary>     /// zip Operations  DotNetZip -based encapsulation      /// </summary>     public static class ziputils      {        /// <summary>          ///  gets the zip stream object of the specified input stream "The original stream object does not change"         /  </summary>         /// <param name= " Sourcestream "></param>         /// <returns></ Returns>         public static stream zipcompress ( stream sourcestream, string entryname =  "Zip")          {            MemoryStream  Compressedstream =&nbSp;new memorystream ();             if  (sourcestream !=  NULL)             {     
           long sourceOldPosition = 0;                 try                  {                     
sourceoldposition = sourcestream.position;                   
  sourceStream.Position = 0;                      using  (Zipfile zip = new zipfile ())                      {                          Zip.
AddEntry (Entryname, sourcestream);                          zip.
Save (Compressedstream);                   
      compressedStream.Position = 0;                   
  }                 }         &nBsp;       catch                  {                 }                  finally                  {                     try                      {                         sourcestream.position =
 sourceOldPosition;                      }                      catch                      {                     }                  }            
 }             return compressedStream;         }         /// < Summary>         ///  get the zip Extract stream object of the specified byte array          ///  the current method only applies to a compressed package that has only one compressed file, that is, only the first compressed file in the compressed package in the method is taken         &nbSp;/// </summary>         /// <param name= " Sourcestream "></param>         /// <returns></ Returns>         public static stream zipdecompress ( Byte[] data)         {       
     stream decompressedstream = new memorystream ();             if  (data != null)              {                 try                  {                      memorystream datastream = new memorystream (data);                      using  (Zipfile zip = zipfile.read (dataStream))                      {                          if  (zip. entries.count > 0)                          {                              zip. Entries.first ().
Extract (Decompressedstream);                          MS is operated in the     // extract method, and the stream position must be returned to zero for subsequent use, otherwise it will result in subsequent reads of no data                               //  returns the Stream object once before returning to zero action                           
   decompressedStream.Position = 0;                          }                      }                  }      &nbSp;          catch                  {                 }            
 }             return decompressedStream;         }         /// < Summary>         ///  Compressed zip file          ///  supports multiple files and multiple directories, or multiple files and multiple directory compression         ///  </summary>         /// <param name= "List" > Files or directory collections to compress </param>         /// <param name= " Strzipname "> file name after compression </param>         /// <param name= "IsDirStruct" > Compression by directory structure </param>         /// <returns> success: true/ Failure:false</returns>         public static bool  Compressmulti (list<string> list, string strzipname, bool isdirstruct)          {             try             {                 using  (zipfile zip =  new zipfile (Encoding.default))//Set encoding to resolve compressed files in Chinese garbled                  {                     foreach  (string path in list)                      {                          string filename = path.getfilename (Path);//Fetch directory name                           //If the directory                          if  (directory.exists (path))                           {                             if  (isdirstruct)//compression by directory structure                               {                                  zip.
Adddirectory (Path, filename);                              }                             Files in the   else//directory are compressed into the zip root directory                              {                                 zip.
Adddirectory (path);                              }                          }                           if  (file.exists (path))//If file                          {                       &Nbsp;      zip.
AddFile (path);                          }                      }                      zip. Save (strzipname);//Compression               
      return true;                 }              }              catch  (Exception)              {                return false;             }          }         /// <summary>          ///  Extract zip file         /// </summary >         /// <param name= "strZipPath" > Zip file to extract < /param>         /// <param name= "StrUnZipPath" > Unpacked directory </param>         /// <param name= "OverWrite" > whether to overwrite </param>         /// <returns> Success: true/failed: false</ Returns>         public static bool decompression ( String strzippath, string strunzippatH, bool overwrite)         {             try              {                
Readoptions options = new readoptions ();                 options. encoding = encoding.default;//set code to solve the Chinese garbled files when extracting                  using  (Zipfile zip = zipfile.read (Strzippath,  options))                  {                     foreach  (Zipentry entry in zip)                      {                         if  (String. IsNullOrEmpty (Strunzippath))                          {                              strunzippath = strzippath.split ('. ').
A ();                          }                          if  (OverWrite)   &NBsp;                      {                             entry. Extract (strunzippath, extractexistingfileaction.overwritesilently)//extract file, overwrite     if already exist                       }                          else                          {                             &nbsP;entry. Extract (strunzippath, extractexistingfileaction.donotoverwrite);/uncompressed file, if existing does not cover                           }                      }               
      return true;                 }              }              catch  (Exception)              {                
return false;             }         }     } 


How to use:

1. Compressed files

list<string> list = new list<string> ();
List.  ADD (@ "D:\Test\ss");
List.  ADD (@ "D:\Test\test1.jpg");
List.  ADD (@ "d:\ company file. txt");
List.  ADD (@ "D:\Test\ss.xml");
BOOL Issuc =ziputils. Compressmulti (list, "D:\\test2.zip", true);
2. extract file
bool issuc = ziputils.decompression ("D:\\test\\test1.zip", "D:\\teest", true);


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.