ASP.Net: Better than Zip - File compression using .Tar.gz Part 2

·

(Cont’d from Part 1)

 

Maybe you’re just renting web space or want to compress file using windows forms or simply don’t like anything not done in ASP.Net then here’s how you do it.

 

Like in my previous posts, import the namespaces….

 

Imports ICSharpCode.SharpZipLib.Tar

Imports ICSharpCode.SharpZipLib.GZip

Imports System.IO

 

The paste the following method in your code…

 

   Sub AddToArchive(ByVal Archive As String, ByVal FolderPath As String, ByVal Files As String)

        Dim gZipStream As New GZipOutputStream(File.Create(Archive))

        Dim TarFile As New TarOutputStream(gZipStream)

 

        For Each s As String In Directory.GetFiles(FolderPath, Files)

            Dim fiEntry As New FileInfo(s)

            Dim fsEntry As FileStream = File.OpenRead(s)

            Dim b(fsEntry.Length - 1) As Byte

            fsEntry.Read(b, 0, b.Length)

 

            Dim thEntry As New TarHeader

            thEntry.Name = fiEntry.Name

            thEntry.Size = fiEntry.Length

            thEntry.ModTime = Now

            Dim TarFileEntry As New TarEntry(thEntry)

            TarFile.PutNextEntry(TarFileEntry)

            TarFile.Write(b, 0, b.Length)

            TarFile.CloseEntry()

            b = Nothing

            TarFileEntry = Nothing

            fsEntry.Close()

            fsEntry.Dispose()

        Next

        TarFile.Finish()

        TarFile.Close()

        TarFile.Dispose()

        gZipStream.Close()

        gZipStream.Dispose()

    End Sub

 

You may then call the method like this…

 

        Dim sArchive As String = "d:\temp\logs.tar.gz"

        Dim sFolder As String = "D:\logs"

        Dim sFiles As String = "*.log"

        AddToArchive(sArchive, sFolder, sFiles)

 

Where  d:\temp\logs.tar.gz is the output filename and directory, D:\logs is the folder where the files to be compressed are located and *.log is the search pattern whereby all files with .log extension will be compressed.

 

 

0 comments: