Saturday, January 19, 2013

C# zip unzip using window shell

If you want to zip / unzip files using C# code .yes its easy and you can do that without using any third party tools. using simple dll (Windows Shell32) you can do that quickly.

Just find below steps.

1.Create new project in Visual Basic 2010.
2.From the main menu, select Project -> Add Reference.
3.Select the COM tab and search for Microsoft Shell Controls and Automation.  



 Try using below code and zip/unzip your code.

Public Class Form1
 
    Sub Zip()
        '1) Lets create an empty Zip File .
        'The following data represents an empty zip file .

        Dim startBuffer() As Byte = {80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, _
                                     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} 
        ' Data for an empty zip file .
        FileIO.FileSystem.WriteAllBytes("d:\empty.zip", startBuffer, False)
 
        'We have successfully made the empty zip file .

        '2) Use the Shell32 to zip your files .
        ' Declare new shell class
        Dim sc As New Shell32.Shell()
        'Declare the folder which contains the files you want to zip .
        Dim input As Shell32.Folder = sc.NameSpace("D:\neededFiles")
        'Declare  your created empty zip file as folder  .
        Dim output As Shell32.Folder = sc.NameSpace("D:\empty.zip")
        'Copy the files into the empty zip file using the CopyHere command .
        output.CopyHere(input.Items, 4)
 
    End Sub
 
    Sub UnZip()
        Dim sc As New Shell32.Shell()
        ''UPDATE !!
        'Create directory in which you will unzip your files .
        IO.Directory.CreateDirectory("D:\extractedFiles") 
        'Declare the folder where the files will be extracted
        Dim output As Shell32.Folder = sc.NameSpace("D:\extractedFiles")
        'Declare your input zip file as folder  .
        Dim input As Shell32.Folder = sc.NameSpace("d:\myzip.zip")
        'Extract the files from the zip file using the CopyHere command .
        output.CopyHere(input.Items, 4)
 
    End Sub
 
End Class
 

1 comment:

  1. hello, I'm trying to unzip using the code you mentioned but this variable - output has value null and hence the copy is not working. can you please advise?

    ReplyDelete