Hi there,
Imports System.IO
Imports ICSharpCode.SharpZipLib.Zip
Imports ICSharpCode.SharpZipLib.Checksums
Namespace MyProject.Services.Compression
Public Class ZipHelper
#Region " Private Shared Methods "
Private Shared Function CreateEntry(ByVal filename As String, ByVal baseFolder As String, ByRef e As ZipEntry) As Byte()
Dim fs As New FileStream(filename, FileMode.Open, FileAccess.Read)
Dim buffer(fs.Length) As Byte
fs.Read(buffer, 0, buffer.Length)
fs.Close()
Dim crc As New Crc32
crc.Reset()
crc.Update(buffer)
Dim entry As New ZipEntry(filename.Replace(baseFolder, "").Trim("/"c, "\"c))
entry.DateTime = DateTime.Now
entry.Size = buffer.Length
entry.Crc = crc.Value
e = entry
Return buffer
End Function
#End Region
#Region " Public Shared Methods "
Public Shared Sub CompressDirectory(ByVal path As String, ByVal target As String)
Dim fs As New FileStream(target, FileMode.Create, FileAccess.Write)
Dim zip As New ZipOutputStream(fs)
zip.SetLevel(9)
Dim PathInfo As New DirectoryInfo(path)
For Each fn As String In Directory.GetFiles(path, "*", SearchOption.AllDirectories)
Dim e As ZipEntry = Nothing
Dim buffer As Byte() = CreateEntry(fn, PathInfo.Parent.FullName, e)
zip.PutNextEntry(e)
zip.Write(buffer, 0, buffer.Length)
Next
zip.Finish()
zip.Close()
fs.Close()
End Sub
Public Shared Sub Decompress(ByVal filename As String, ByVal target As String)
Dim fs As New FileStream(filename, FileMode.Open, FileAccess.Read)
Dim zip As New ZipInputStream(fs)
Dim entry As ZipEntry
While (True)
entry = zip.GetNextEntry
If (IsNothing(entry)) Then Exit While
Dim data(entry.Size) As Byte
zip.Read(data, 0, entry.Size)
Dim trg As String = Path.Combine(target, Path.GetDirectoryName(entry.Name))
If (Not Directory.Exists(trg)) Then
Directory.CreateDirectory(trg)
End If
If (Not entry.IsDirectory) Then
Dim fs2 As New FileStream(Path.Combine(target, entry.Name), FileMode.Create, FileAccess.Write)
fs2.Write(data, 0, entry.Size)
fs2.Flush()
fs2.Close()
End If
End While
zip.Close()
fs.Close()
End Sub
#End Region
End Class
End Namespace
Using Example :
ZipHelper.CompressDirectory(Path.Combine(installingPath, "Data"), Path.Combine(Common.LavanConfig.BackupDestination, String.Format("{0}.zip", DateTime.Now.Year & "-" & DateTime.Now.Month & "-" & DateTime.Now.Day & "-" & DateTime.Now.Hour & "-" & DateTime.Now.Minute)))
Download SharpZipLib : http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx
Convert to C# : http://labs.developerfusion.co.uk/convert/vb-to-csharp.aspx
Enter your message below
Sign in or Join us (it's free).