Common zip class libraries in. Net: sharpziplib, J # zip library, and zlib. net.
In. Net 3.0, system. Io. Packaging. zippackage is added, and third-party Lib is no longer needed.
1 Using System;
2 Using System. Collections. Generic;
3 Using System. IO;
4 Using System. Io. packaging;
5
6 Public Class Sharpzip
7 {
8 Private Const Long Buffer_size = 4096 ;
9
10 Public Static Void Compressfiles (list < String > Filenames, String Zipfilename)
11 {
12 Foreach ( String File In Filenames)
13 {
14 Compressfile (zipfilename, file );
15 }
16 }
17
18 Public Static Void Compressfile ( String Zipfilename, String Filetoadd)
19 {
20 Using (Package zip = System. Io. Packaging. Package. Open (zipfilename, filemode. openorcreate ))
21 {
22 String Destfilename = " .\\ " + Path. getfilename (filetoadd );
23 Uri URI = Packurihelper. createparturi ( New Uri (destfilename, urikind. Relative ));
24 If (Zip. partexists (URI ))
25 {
26 Zip. deletepart (URI );
27 }
28 Packagepart part = Zip. createpart (Uri, "" , Compressionoption. Normal );
29 Using (Filestream = New Filestream (filetoadd, filemode. Open, fileaccess. Read ))
30 {
31 Using (Stream dest = Part. getstream ())
32 {
33 Copystream (filestream, DEST );
34 }
35 }
36 }
37 }
38
39 Public Static Void Decompressfile ( String Zipfilename, String Outpath)
40 {
41 Using (Package zip = System. Io. Packaging. Package. Open (zipfilename, filemode. Open ))
42 {
43 Foreach (Packagepart part In Zip. getparts ())
44 {
45 String Outfilename = Path. Combine (outpath, part. Uri. originalstring. substring ( 1 ));
46 Using (System. Io. filestream outfilestream = New System. Io. filestream (outfilename, filemode. Create ))
47 {
48 Using (Stream infilestream = Part. getstream ())
49 {
50 Copystream (infilestream, outfilestream );
51 }
52 }
53 }
54 }
55 }
56
57 Private Static Void Copystream (system. Io. Stream inputstream, system. Io. Stream outputstream)
58 {
59 Long Buffersize = Inputstream. Length < Buffer_size ? Inputstream. Length: buffer_size;
60 Byte [] Buffer = New Byte [Buffersize];
61 Int Bytesread = 0 ;
62 Long Byteswritten = 0 ;
63 While (Bytesread = Inputstream. Read (buffer, 0 , Buffer. Length )) ! = 0 )
64 {
65 Outputstream. Write (buffer, 0 , Bytesread );
66 Byteswritten + = Buffersize;
67 }
68 }
69 }