Hello, can someone help me with this or present other method to do this.
- If i select single file for Archive then to execute the Single File Zip code, If i select folder directory path to Zip to execute the Folder Execute code
- Progressbar to use only 1 progress bar to count total progress + inside the progressbar to show persentages 25% done, 26% and so one.
- Display information from Zip or Unzip inside Textbox,Listview or other like in the image
code is working fine,
but my questions are:
- how to make button for example to select single file or folder path.
If i select single file will use code "Zip single file"
If i select folder path will use code "zip folder" function
And another button2:
Add path directory for Unzip where to unzip it and how to name the file.
Imports System.ComponentModel
Imports System.Threading
Imports Ionic.Zip
Public Class Form1
    Public Class WorkerOptions
        ' Fields
        'Public Comment As String
        'Public CompressionLevel As CompressionLevel
        'Public Encoding As String
        'Public Encryption As EncryptionAlgorithm
        Public Folder As String
        'Public Password As String
        'Public Zip64 As Zip64Option
        'Public ZipFlavor As Integer
        Public ZipName As String
        Public File As String
    End Class
    ' Delegates for invocation of UI from other threads
    Private Delegate Sub SaveEntryProgress(ByVal e As SaveProgressEventArgs)
    Private Delegate Sub Buttonclick(ByVal sender As Object, ByVal e As EventArgs)
    Private Delegate Sub FileExtractProgressDel(ByVal sender As Object, ByVal e As ExtractProgressEventArgs)
    Private Delegate Sub SetStatusTextInvoker(ByVal Text As String)
    Private _workerThread As Thread
    Private _saveCanceled As Boolean
    Private _totalBytesAfterCompress As ULong
    Private _totalBytesBeforeCompress As ULong
    Private _nFilesCompleted As ULong
    Private _progress2MaxFactor As ULong
    Private _entriesToZip As ULong
    Private TotalSize As ULong = 0
    Private ExtractedSize As ULong = 0
    Private LastBtsTransfered As ULong = 0
    Private BufferSize As ULong = 0
    Dim TargetDir As String = ""
    Dim zip1 As ZipFile = Nothing
    Dim FicheiroJaExtraidos As Integer = 0
    Private Sub KickoffZipup()
        'Dim fileName As String = "d:\somefolder\4.5GB-dummy.txt"
        Dim pasta As String = "D:\YouTube"
        Me._saveCanceled = False
        Me._totalBytesAfterCompress = 0
        Me._totalBytesBeforeCompress = 0
        Me.btnZipUp.Enabled = False
        Me.btnZipUp.Text = "Zipping..."
        Me.btnCancel.Enabled = True
        Me.lblStatus.Text = "Verifying selected folder..."
        'options.File = fileName' to zip only one file
        Dim options As New WorkerOptions With {
            .ZipName = "D:\zipFileCreated.zip",
            .Folder = pasta 'to zip a full folder
            }
        Me._workerThread = New Thread(AddressOf DoSave) With {
            .Name = "Zip Saver thread"
        }
        Me._workerThread.Start(options)
        Me.Cursor = Cursors.WaitCursor 'change cursor to wait mode
    End Sub
    Private Sub DoSave(ByVal p As Object)
        Dim options As WorkerOptions = TryCast(p, WorkerOptions)
        
        '******************zip a full folder***********************
        Try
            Using zip1 As New ZipFile
                'this is necessary because ZIP can become corrupted if this is activated, however, compression is slower
                zip1.ParallelDeflateThreshold = -1
                If TextBox_Password.Text <> Nothing Then
                    zip1.Password = TextBox_Password.Text   ' this is the password to UNzip
                    zip1.Encryption = EncryptionAlgorithm.WinZipAes256  ' encryption of the ZIP
                Else
                    zip1.Password = Nothing 'no password, user didn't input a password
                End If
                zip1.AlternateEncoding = System.Text.Encoding.UTF8 ' this will solve the error "illegal characters in path"
                zip1.AlternateEncodingUsage = ZipOption.AsNecessary ' and this will solve the same error above
                zip1.AddDirectory(options.Folder)
                Me._entriesToZip = zip1.EntryFileNames.Count
                Me.SetProgressBars()
                AddHandler zip1.SaveProgress,
               New EventHandler(Of SaveProgressEventArgs)(AddressOf Me.zip1_SaveProgress)
                zip1.UseZip64WhenSaving = Zip64Option.Always 'ZIP64 allows you to exceed 4gb in a zip, or 65535 entries in a zip.
                zip1.Save(options.ZipName)
            End Using
        Catch exc1 As Exception
            MessageBox.Show(String.Format("Exception while zipping: {0}", exc1.Message))
            Me.btnCancel_Click(Nothing, Nothing)
        End Try
        '****************** /zip a full folder ***********************
    End Sub
    Private Sub SetProgressBars()
        If Me.ProgressBar1.InvokeRequired Then
            'Me.ProgressBar1.Invoke(New MethodInvoker(Me, DirectCast(Me.SetProgressBars, IntPtr)))
            Me.ProgressBar1.Invoke(New MethodInvoker(AddressOf SetProgressBars))
        Else
            Me.ProgressBar1.Value = 0
            Me.ProgressBar1.Maximum = Me._entriesToZip
            Me.ProgressBar1.Minimum = 0
            Me.ProgressBar1.Step = 1
            Me.ProgressBar2.Value = 0
            Me.ProgressBar2.Minimum = 0
            Me.ProgressBar2.Maximum = 1
            Me.ProgressBar2.Step = 2
        End If
    End Sub
    Private Sub zip1_SaveProgress(ByVal sender As Object, ByVal e As SaveProgressEventArgs)
        Select Case e.EventType
            Case ZipProgressEventType.Saving_AfterWriteEntry
                Me.StepArchiveProgress(e)
                Exit Select
            Case ZipProgressEventType.Saving_Completed
                Me.SaveCompleted()
                Exit Select
            Case ZipProgressEventType.Saving_EntryBytesRead
                Me.StepEntryProgress(e)
                Exit Select
        End Select
        If Me._saveCanceled Then
            e.Cancel = True
        End If
    End Sub
    Private Sub StepArchiveProgress(ByVal e As SaveProgressEventArgs)
        If Me.ProgressBar1.InvokeRequired Then
            Me.ProgressBar1.Invoke(New SaveEntryProgress(AddressOf Me.StepArchiveProgress), New Object() {e})
        ElseIf Not Me._saveCanceled Then
            Me._nFilesCompleted += 1
            Me.ProgressBar1.PerformStep()
            Me._totalBytesAfterCompress = (Me._totalBytesAfterCompress + e.CurrentEntry.CompressedSize)
            Me._totalBytesBeforeCompress = (Me._totalBytesBeforeCompress + e.CurrentEntry.UncompressedSize)
            ' progressBar2 is the one dealing with the item being added to the archive
            ' if we got this event, then the add of that item (or file) is complete, so we
            ' update the progressBar2 appropriately.
            Me.ProgressBar2.Value = Me.ProgressBar2.Maximum = 1
            MyBase.Update()
        End If
    End Sub
    Private Sub SaveCompleted()
        If Me.lblStatus.InvokeRequired Then
            Me.lblStatus.Invoke(New MethodInvoker(AddressOf SaveCompleted))
            'Me.lblStatus.Invoke(New MethodInvoker(Me, DirectCast(Me.SaveCompleted, IntPtr)))
        Else
            Me.lblStatus.Text = String.Format("Done, Compressed {0} files, {1:N0}% of original",
                                              Me._nFilesCompleted,
                                              ((100 * Me._totalBytesAfterCompress) /
                                               CDbl(Me._totalBytesBeforeCompress)))
            Me.ResetState()
        End If
    End Sub
    Private Sub StepEntryProgress(ByVal e As SaveProgressEventArgs)
        If Me.ProgressBar2.InvokeRequired Then
            Me.ProgressBar2.Invoke(New SaveEntryProgress(AddressOf Me.StepEntryProgress), New Object() {e})
        ElseIf Not Me._saveCanceled Then
            If (Me.ProgressBar2.Maximum = 1) Then
                Dim entryMax As Long = e.TotalBytesToTransfer
                Dim absoluteMax As Long = &H7FFFFFFF
                Me._progress2MaxFactor = 0
                Do While (entryMax > absoluteMax)
                    entryMax = (entryMax / 2)
                    Me._progress2MaxFactor += 1
                Loop
                If (CInt(entryMax) < 0) Then
                    entryMax = (entryMax * -1)
                End If
                Me.ProgressBar2.Maximum = CInt(entryMax)
            End If
            '####################################################
            '####################################################
            '   HERE IS WHERE I AM GETTING THE OVERFLOW ERROR
            '####################################################
            '####################################################
            Dim xferred As ULong = CULng((e.BytesTransferred >> Me._progress2MaxFactor))
            Me.ProgressBar2.Value = IIf((xferred >= Me.ProgressBar2.Maximum),
                                    Me.ProgressBar2.Maximum,
                                    xferred)
            Dim Porcentagem As Integer
            Porcentagem = ProgressBar1.Value / ProgressBar1.Maximum * 100 ' get percentage
            Me.lblStatus.Text = String.Format(Porcentagem & "%" & "  ---->  " & "{0} of {1} files...({2})", (Me._nFilesCompleted + 1), Me._entriesToZip, e.CurrentEntry.FileName)
            MyBase.Update()
        End If
    End Sub
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    End Sub
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnZipUp.Click
        Me.KickoffZipup() 'start zipping
    End Sub
    Private Sub ResetState()
        'cancel zipping
        'Me.btnCancel.Enabled = False
        Me.btnZipUp.Enabled = True
        Me.btnZipUp.Text = "Zip it!"
        Me.ProgressBar1.Value = 0
        Me.ProgressBar2.Value = 0
        Me.Cursor = Cursors.Default
        'If Not Me._workerThread.IsAlive Then
        '    Me._workerThread.Join()
        'End If
        '/cancel zipping
    End Sub
    Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
        If Me.lblStatus.InvokeRequired Then
            Me.lblStatus.Invoke(New Buttonclick(AddressOf Me.btnCancel_Click), New Object() {sender, e})
        Else
            Me._saveCanceled = True
            Me.ResetState()
        End If
        Me.lblStatus.Text = "Canceled..."
    End Sub
    Private Sub btn_extract_Click(sender As Object, e As EventArgs) Handles btn_extract.Click
        Dim ZipToUnpack As String = "D:\zipFileCreated.zip"
        TargetDir = "D:\UnzipNew\"
        zip1 = ZipFile.Read(ZipToUnpack)
        AddHandler zip1.ExtractProgress, AddressOf FileExtractProgress
        'reset these values each time you unzip a folder
        BufferSize = CULng(zip1.BufferSize)
        TotalSize = 0
        ExtractedSize = 0
        'get the total size in bytes to be extracted
        For Each ent As ZipEntry In zip1
            TotalSize += CULng(ent.UncompressedSize)
        Next
        'if the total size is greater than Integer.MaxValue then divide it down by 1024 before setting the ProgressBar.Maximum
        If TotalSize >= Integer.MaxValue Then
            ProgressBar1.Maximum = CInt(TotalSize / 1024)
        Else
            ProgressBar1.Maximum = CInt(TotalSize)
        End If
        'start the BackgroundWorker and pass the ZipFile to it as an Argument
        BackgroundWorker1.RunWorkerAsync(zip1)
    End Sub
    Private Sub FileExtractProgress(ByVal sender As Object, ByVal e As ExtractProgressEventArgs)
        'check if the form requires to be invoked and invoke a new FileExtractProgressDel delagate
        If Me.InvokeRequired Then
            Me.Invoke(New FileExtractProgressDel(AddressOf FileExtractProgress), New Object() {sender, e})
        Else
            'if the reported BytesTransferred is greater than 0 then add the number of bytes that where transferred to the ExtractedSize variable
            'and set the LastBtsTransfered to the number of bytes that have been transferred so far. Else reset the LastBtsTransfered to 0.
            If e.BytesTransferred > 0 Then
                ExtractedSize += CULng(e.BytesTransferred - LastBtsTransfered)
                LastBtsTransfered = CULng(e.BytesTransferred)
            Else
                LastBtsTransfered = 0
            End If
            'again, if the total size is greater than Integer.MaxValue then divide the ExtractedSize by 1024 before setting the ProgressBar.Value
            If TotalSize >= Integer.MaxValue Then
                ProgressBar1.Value = CInt(ExtractedSize / 1024)
            Else
                ProgressBar1.Value = CInt(ExtractedSize)
            End If
        End If
    End Sub
    Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        'cast the argument Object type back into a ZipFile type
        Dim zfile As ZipFile = CType(e.Argument, ZipFile)
        'extract the file(s)
        'iterate through the entries and unzip them here in the separate thread
        For Each ent As ZipEntry In zfile
            If (Not ent.IsDirectory) And ent.UsesEncryption Then
                zip1.Password = "password" 'this is the password that was used when the file was zipped
                ' this file HAS a password
                ent.Extract(TargetDir, ExtractExistingFileAction.OverwriteSilently)
                FicheiroJaExtraidos = FicheiroJaExtraidos + 1 'count extracted files
            Else
                ' this file DOESN'T HAVE a password
                ent.Extract(TargetDir, ExtractExistingFileAction.OverwriteSilently)
                FicheiroJaExtraidos = FicheiroJaExtraidos + 1 'count extracted files
            End If
            Dim Porcentagem As Integer
            Porcentagem = ProgressBar1.Value / ProgressBar1.Maximum * 100 ' get percentage
            SetStatusText(String.Format(Porcentagem & "%" & "  ---->  " & "{0} of {1} files...({2})", (FicheiroJaExtraidos), zip1.EntryFileNames.Count, ent.FileName))
        Next
    End Sub
    Private Sub SetStatusText(ByVal Text As String)
        ' System.Threading.Thread.Sleep(6) ' not needed but here for future reference
        If Me.InvokeRequired Then
            Me.Invoke(New SetStatusTextInvoker(AddressOf SetStatusText), Text)
        Else
            lblStatus.Text = Text
        End If
    End Sub
    Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
        zip1.Dispose() 'dispose the ZipFile that was created and passed to the BackgroundWorker
        zip1 = Nothing
        SetStatusText("Extraction complete!")
    End Sub
End Class