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
| Imports System.IO
Imports System.IO.Packaging
Namespace ZipSample
Class Program
Shared Sub Main(args As String())
AddFileToZip("Output.zip", "C:\Windows\Notepad.exe")
AddFileToZip("Output.zip", "C:\Windows\System32\Calc.exe")
End Sub
Private Const BUFFER_SIZE As Long = 4096
Private Shared Sub AddFileToZip(zipFilename As String, fileToAdd As String)
Using zip As Package = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate)
Dim destFilename As String = ".\" + Path.GetFileName(fileToAdd)
Dim uri As Uri = PackUriHelper.CreatePartUri(New Uri(destFilename, UriKind.Relative))
If zip.PartExists(uri) Then
zip.DeletePart(uri)
End If
Dim part As PackagePart = zip.CreatePart(uri, "", CompressionOption.Normal)
Using fileStream As New FileStream(fileToAdd, FileMode.Open, FileAccess.Read)
Using dest As Stream = part.GetStream()
CopyStream(fileStream, dest)
End Using
End Using
End Using
End Sub
Private Shared Sub CopyStream(inputStream As System.IO.FileStream, outputStream As System.IO.Stream)
Dim bufferSize As Long = If(inputStream.Length < BUFFER_SIZE, inputStream.Length, BUFFER_SIZE)
Dim buffer As Byte() = New Byte(bufferSize - 1) {}
Dim bytesRead As Integer = 0
Dim bytesWritten As Long = 0
While (InlineAssignHelper(bytesRead, inputStream.Read(buffer, 0, buffer.Length))) <> 0
outputStream.Write(buffer, 0, bytesRead)
bytesWritten += bufferSize
End While
End Sub
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
target = value
Return value
End Function
End Class
End Namespace |
Partager