. Net built-in library to generate zip files

Source: Internet
Author: User
Tags zip folder

Here is an example:

    Create a folder that can contain any subdirectory.

    Create a console project and add a class ZipManager to implement the operations we want.

    Add a WindowsBase reference for the project. (This name is unfriendly, but the class related to compression is hidden in it)

    Add a reference to the System. IO. Packaging namespace in ZipManager. cs.

    Write a constructor to receive the file path to be compressed.

    Create a ZipFolder method to perform the actual compression operation. Create a Package instance in this method.

    Create a function called ZipDirectory to recursively traverse all subdirectories and subfolders.

    Create a PackagePart instance for each file.

    Note that the relative path generation process is as follows: take more parts than the Source Path and replace the right slash with the left slash.

    Copy the content of the source file to the Package. Therefore, you need to add a CopyStream method.

    The ZipManager class is complete. Now let's call this class.

    Run this program. A zip folder is generated at the specified location.

    Double-click to open it.

Comments:

This example only shows the function provided by. net. For this example, we can extend it well. The following are some extensions:

1. Apply the System. IO. Packaging. PackUriHelper class to conveniently generate the PackagePart Uri. You must generate the Uri as in the example.

2. The third parameter in the Package. CreatePart (Uri, String, CompressionOption) method provides the compression method.

3. More tips can be seen here: http://msdn.microsoft.com/zh-cn/library/system.io.packaging.aspx

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.