Loại: Class
Ngôn ngữ lập trình: VB.NET
Tác giả: Băng Nhât Quang
Chức năng: Hỗ trợ nén và giải nén file
Mô tả:: Hỗ trợ từ .NET 2008 trở đi
Nguồn: Đi chôm một nơi một ít về gom lại thôi! Không phải chính hãng đâu

- Imports System.IO
- Imports System.IO.Compression
- Public Class _ClsGZip
- Public Function CompressFile(ByRef _file As String, ByRef _folderSave As String) As String
- ' Kiểm tra file đem nén
- If IO.File.Exists(_file) = False Then
- Return "File này không có"
- Exit Function
- Else
- 'Kiểm tra folder save
- If IO.Directory.Exists(_folderSave) = False Then
- Return "Folder này làm gì có"
- Exit Function
- End If
- End If
- Try
- 'Lấy tên file
- Dim name As String = Path.GetFileName(_file)
- 'Chuyển file thành mảng byte()
- Dim source() As Byte = System.IO.File.ReadAllBytes(_file)
- 'Nén mảng byte()
- Dim compressed() As Byte = ConvertToByteArray(source)
- 'Sau khi đã nén file thì bây giờ write nó lại thôi
- System.IO.File.WriteAllBytes(_folderSave & "\" & name & ".zip", compressed)
- Return "Nén thành công!"
- Catch ex As Exception
- Return "Nén bị lỗi: " & ex.ToString()
- End Try
- End Function
- Public Function DecompressFile(ByRef _FileNen As String, ByRef _FilegiaiNen As String) As Boolean
- Try
- Dim _MemoryStream As New MemoryStream(File.ReadAllBytes(_FileNen))
- ' giải nén Gzip
- Dim _GZipStream As New GZipStream(_MemoryStream, CompressionMode.Decompress)
- Dim _temp(3) As Byte
- 'Đọc từ stream
- _MemoryStream.Position = _MemoryStream.Length - 5
- _MemoryStream.Read(_temp, 0, 4)
- ' Tính kích của mảng byte giải nén
- Dim _size As Integer = BitConverter.ToInt32(_temp, 0)
- 'Vị trí bắt đầu của Stream
- _MemoryStream.Position = 0
- Dim _ByteGNen(_size - 1) As Byte
- 'Đoc byte đã giải nén vào mảng byte
- _GZipStream.Read(_ByteGNen, 0, _size)
- 'Giải phóng bộ nhớ
- _GZipStream.Dispose()
- _MemoryStream.Dispose()
- 'Viết lại file gốc
- File.WriteAllBytes(_FilegiaiNen, _ByteGNen)
- Return True
- Catch ex As Exception
- MessageBox.Show(ex.ToString())
- Return False
- End Try
- End Function
- Public Function ConvertToByteArray(ByVal _source() As Byte) As Byte()
- 'Tạo một MemoryStream mới
- Dim _MemoryStream As New MemoryStream()
- 'Khởi tạo GZipStream, nén : Cái này là của Gzip: nén thế nào thì tui chịu
- Dim _GZipStream As New GZipStream(_MemoryStream, CompressionMode.Compress, True)
- 'Viết mảng byte() sau khi nén vào biến source
- _GZipStream.Write(_source, 0, _source.Length)
- 'Xóa sạch
- _GZipStream.Dispose()
- _MemoryStream.Position = 0
- Dim _temp(_MemoryStream.Length) As Byte
- _MemoryStream.Read(_temp, 0, _temp.Length)
- _MemoryStream.Dispose()
- Return _temp
- End Function
- End Class