. NET is also crazy: generate a zip file

Source: Internet
Author: User
Tags zip folder

When we create a zip file, we can either use a ready-made software or a third-party open-source library. In fact, it is very convenient to use the class operations that come with. net. Here is an example:

    1. Create a folder that can contain any subdirectory.

       

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

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

    4. Add a reference to the system. Io. Packaging namespace in zipmanager. CS.

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

    6. Create a zipfolder method to perform the actual compression operation. Create a package instance in this method.

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

    8. 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.

    9. Copy the content of the source file to the package. Therefore, you need to add a copystream method.

    10. The zipmanager class is complete. Now let's call this class.

    11. Run thisProgramIn the specified location, a ZIP folder is generated.

      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

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.