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:
- 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 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