1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| Imports System
Imports System.IO
Imports ICSharpCode.SharpZipLib.Core
Imports ICSharpCode.SharpZipLib.Zip
' Compresses the files in the nominated folder, and creates a zip file on disk named as outPathname.
'
Public Sub CreateSample(outPathname As String, password As String, folderName As String)
Dim fsOut As FileStream = File.Create(outPathname)
Dim zipStream As New ZipOutputStream(fsOut)
zipStream.SetLevel(3) '0-9, 9 being the highest level of compression
zipStream.Password = password ' optional. Null is the same as not setting.
' This setting will strip the leading part of the folder path in the entries, to
' make the entries relative to the starting folder.
' To include the full path for each entry up to the drive root, assign folderOffset = 0.
Dim folderOffset As Integer = folderName.Length + (If(folderName.EndsWith("\"), 0, 1))
CompressFolder(folderName, zipStream, folderOffset)
zipStream.IsStreamOwner = True
' Makes the Close also Close the underlying stream
zipStream.Close()
End Sub
' Recurses down the folder structure
'
Private Sub CompressFolder(path As String, zipStream As ZipOutputStream, folderOffset As Integer)
Dim files As String() = Directory.GetFiles(path)
For Each filename As String In files
Dim fi As New FileInfo(filename)
Dim entryName As String = filename.Substring(folderOffset) ' Makes the name in zip based on the folder
entryName = ZipEntry.CleanName(entryName) ' Removes drive from name and fixes slash direction
Dim newEntry As New ZipEntry(entryName)
newEntry.DateTime = fi.LastWriteTime ' Note the zip format stores 2 second granularity
' Specifying the AESKeySize triggers AES encryption. Allowable values are 0 (off), 128 or 256.
' newEntry.AESKeySize = 256;
' To permit the zip to be unpacked by built-in extractor in WinXP and Server2003, WinZip 8, Java, and other older code,
' you need to do one of the following: Specify UseZip64.Off, or set the Size.
' If the file may be bigger than 4GB, or you do not need WinXP built-in compatibility, you do not need either,
' but the zip will be in Zip64 format which not all utilities can understand.
' zipStream.UseZip64 = UseZip64.Off;
newEntry.Size = fi.Length
zipStream.PutNextEntry(newEntry)
' Zip the file in buffered chunks
' the "using" will close the stream even if an exception occurs
Dim buffer As Byte() = New Byte(4095) {}
Using streamReader As FileStream = File.OpenRead(filename)
StreamUtils.Copy(streamReader, zipStream, buffer)
End Using
zipStream.CloseEntry()
Next
Dim folders As String() = Directory.GetDirectories(path)
For Each folder As String In folders
CompressFolder(folder, zipStream, folderOffset)
Next
End Sub |
Partager