Imports System.IO
Imports System.IO.Compression
Public Class ZipUtility
Public Sub CompressFile(ByVal sourceFile As String, ByVal destinationFile As String)
' 判断来源文件是否存在。如果不存在则掷回例外状况 FileNotFoundException。
If File.Exists(sourceFile) = False Then
Throw New FileNotFoundException
End If
' 宣告所要使用的字节数组并将其初值设定为 Nothing。
Dim buffer As Byte() = Nothing
Try
' 建立一个 FileStream 对象来开启并读取所要压缩的文件。
Using sourceStream As New FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read)
' 建立一个字节数组并将其大小设定为 sourceStream 的长度。
'buffer = New Byte(sourceStream.Length - 1) {}
ReDim buffer(sourceStream.Length - 1)
' 将 sourceStream 对象的内容写入到字节数组 buffer 中,
' 并建立整数变量 checkCounter 来接收 Read 方法回传之成功读取的长度值。
Dim checkCounter As Integer = sourceStream.Read(buffer, 0, buffer.Length)
' 建立一个 FileStream 对象来建立并写入一个新文件,此新文件就是用来存放压缩后之数据的压缩文件。
Using destinationStream As New FileStream(destinationFile, FileMode.OpenOrCreate, FileAccess.Write)
' 使用目标文件的数据流 destinationStream 来建立一个 GZipStream 对象。
Using compressedStream As New GZipStream(destinationStream, CompressionMode.Compress, True)
' 压缩字节数组中的数据并将压缩后的数据写入基础数据流中。
compressedStream.Write(buffer, 0, buffer.Length)
End Using
End Using
End Using
' 处理程序执行过程中所掷回的 ApplicationException 例外状况。
Catch ex As ApplicationException
本内容试读结束,登录后可阅读更多
下载后可阅读完整内容,剩余3页未读,立即下载