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