home *** CD-ROM | disk | FTP | other *** search
/ Chip 2002 September / Chip_2002-09_cd1.bin / zkuste / vbasic / Data / Utils / XZipNet.msi / Data1.cab / ZipDemo.vb < prev    next >
Encoding:
Text File  |  2002-02-04  |  15.5 KB  |  445 lines

  1. 'Xceed Zip for .NET - StreamDemo for VB.NET Sample Application
  2. 'Copyright (c) 2000-2002 - Xceed Software Inc
  3. '
  4. '[ZipDemo.vb]
  5. '
  6. 'This console application demonstrates how to perform basic zip file manipulations.
  7. '
  8. 'This file is part of Xceed Zip for .NET. The source code in this file
  9. 'is only intended as a supplement to the documentation and is provided "as is"
  10. 'without warranty of any kind, either expresed or implied.
  11.  
  12. Imports System
  13. Imports System.IO
  14. Imports Xceed.FileSystem
  15. Imports Xceed.Zip
  16.  
  17. Module Module1
  18.  
  19.   'Create a FileSystemEvents object for handling the ItemProgression event
  20.   Dim WithEvents m_events As New FileSystemEvents()
  21.  
  22. #Region " Zipfile listing methods "
  23.  
  24.   'Lists the contents of a zip file based on a file mask (wildcard) and displays
  25.   'the results in a non-formatted list on the console.
  26.   '
  27.   'zipFilename is the name of the zip file. The zip file MUST exist.
  28.   'fileMask is the wildcard that is used to filter the list output.
  29.   Public Sub ListZip(ByVal zipFilename As String, ByVal fileMask As String)
  30.  
  31.     'Create a DiskFile object for the specified zip filename
  32.     Dim zipFile As New DiskFile(zipFilename)
  33.  
  34.     If Not zipFile.Exists Then
  35.       Console.WriteLine("The specified zip file does not exist.")
  36.       Return
  37.     End If
  38.  
  39.     Console.WriteLine("Listing all files matching the mask {0} contained in {1}...", fileMask, zipFilename)
  40.     Console.WriteLine()
  41.  
  42.     'Create a ZipArchive object to access the zip file
  43.     Dim zip As New ZipArchive(zipFile)
  44.  
  45.     'Obtain a flat array of all files contained in the zip file and it's subfolders.
  46.     Dim files() As AbstractFile = zip.GetFiles(True, fileMask)
  47.  
  48.     Dim file As AbstractFile
  49.     For Each file In files
  50.       Console.WriteLine(file.FullName)
  51.     Next
  52.  
  53.     Console.WriteLine()
  54.  
  55.     If (files.Length = 0) Then
  56.       Console.WriteLine("The zip file is empty or it does not contain any file matching the specified mask.")
  57.     Else
  58.       Console.WriteLine("{0} files.", files.Length)
  59.     End If
  60.  
  61.   End Sub
  62.  
  63.   'Lists the contents of a zip file based on a file mask (wildcard) and displays
  64.   'the results folder by folder.
  65.   '
  66.   'zipFilename is the name of the zip file. The zip file MUST exist.
  67.   'fileMask is the wildcard that is used to filter the list output.
  68.   Public Sub ListZipByFolder(ByVal zipFilename As String, ByVal fileMask As String)
  69.  
  70.     'Create a DiskFile object for the specified zip filename.
  71.     Dim zipFile As New DiskFile(zipFilename)
  72.  
  73.     If Not zipFile.Exists Then
  74.       Console.WriteLine("The specified zip file does not exist.")
  75.       Return
  76.     End If
  77.  
  78.     Console.WriteLine("Listing all the files matching the mask {0} contained in {1}, folder by folder...", fileMask, zipFilename)
  79.     Console.WriteLine()
  80.  
  81.     'Create  a ZipArchive object to access the zip file
  82.     Dim zip As New ZipArchive(zipFile)
  83.  
  84.     'Since the ZipArchive class derives from the ZippedFolder class which in turn
  85.     'derives from the AbstractFolder class, we can directly call a utility method 
  86.     'that lists the contents of an AbstractFolder recursively.
  87.     ListFolder(zip, fileMask)
  88.   End Sub
  89.  
  90.   'Utility method that lists the contents of a folder in a zip file and calls 
  91.   'itself recursively for subfolders.
  92.   Public Sub ListFolder(ByVal folder As AbstractFolder, ByVal fileMask As String)
  93.  
  94.     Console.WriteLine()
  95.     Console.WriteLine("Listing of " + folder.FullName)
  96.     Console.WriteLine()
  97.  
  98.     'Obtain an array of files contained in the current folder
  99.     Dim files() As AbstractFile = folder.GetFiles(False, fileMask)
  100.  
  101.     'Iterate on the returned array of AbstractFile objects and print
  102.     'the details of each file.
  103.     Dim file As AbstractFile
  104.  
  105.     For Each file In files
  106.       Console.WriteLine("{0} " + vbTab + "{1} " + vbTab + "{2} " + vbTab + "{3}", file.LastWriteDateTime.ToShortDateString(), file.LastWriteDateTime.ToShortTimeString(), file.Size, file.Name)
  107.     Next
  108.  
  109.     Console.WriteLine()
  110.     Console.WriteLine("{0} files.", files.Length)
  111.  
  112.     'Call ListFolder recursively for the subfolders of the current folder
  113.     Dim subFolder As AbstractFolder
  114.  
  115.     For Each subFolder In folder.GetFolders(False)
  116.       ListFolder(subFolder, fileMask)
  117.     Next
  118.   End Sub
  119.  
  120. #End Region
  121.  
  122. #Region " Zipfile extraction methods "
  123.  
  124.   'Extracts the contents of a zip file to a specified folder based on a filemask (wilcard)
  125.   Public Sub ExtractZip(ByVal zipFilename As String, ByVal destFolder As String, ByVal fileMask As String, ByVal password As String)
  126.  
  127.     'Create a DiskFile object for the specified zip filename
  128.     Dim zipFile As New DiskFile(zipFilename)
  129.  
  130.     If Not zipFile.Exists Then
  131.       Console.WriteLine("The specified zip file does not exist.")
  132.       Return
  133.     End If
  134.  
  135.     Console.WriteLine("Extracting all files matching the mask {0} to {1}...", fileMask, destFolder)
  136.     Console.WriteLine()
  137.  
  138.     'Create a ZipArchive object to access the zip file
  139.     Dim zip As New ZipArchive(zipFile)
  140.     zip.DefaultDecryptionPassword = password
  141.  
  142.     'Create a DiskFolder object for the destination folder
  143.     Dim destinationFolder As New DiskFolder(destFolder)
  144.  
  145.     'Copy the contents of the zip file to the destination folder
  146.     zip.CopyFilesTo(m_events, "Extracting", destinationFolder, True, True, fileMask)
  147.   End Sub
  148.  
  149. #End Region
  150.  
  151. #Region " Zip update methods "
  152.  
  153.   'Adds files to a zip file
  154.   '
  155.   'zipFilename is the anme of the zip file. If it does not exist, it will be created. 
  156.   'If it exists, it will be updated.
  157.   '
  158.   'sourceFolder is the name of the folder from which the files will be added.
  159.   'fileMask is the name of the file to add to the zip file. It can include wildcards.
  160.   'recursive specifies if the files in the subfolders of sourceFolder should also be added.
  161.   Public Sub AddFilesToZip(ByVal zipFilename As String, ByVal sourceFolder As String, ByVal fileMask As String, ByVal recursive As Boolean, ByVal password As String)
  162.  
  163.     If (sourceFolder.Length = 0) Then
  164.       Throw New ArgumentException("You must specify a source folder from which files will be added to the zip file.", "sourceFolder")
  165.     End If
  166.  
  167.     'Create a DiskFile object for the specified zip filename
  168.     Dim zipFile As New DiskFile(zipFilename)
  169.  
  170.     'Check if the file exists
  171.     If Not zipFile.Exists Then
  172.       Console.WriteLine("Creating a new zip file {0}...", zipFilename)
  173.       zipFile.Create()
  174.     Else
  175.       Console.WriteLine("Updating existing zip file {0}...", zipFilename)
  176.     End If
  177.  
  178.     Console.WriteLine()
  179.  
  180.     'Create a ZipArchive object to access the zip file
  181.     Dim zip As New ZipArchive(zipFile)
  182.     zip.DefaultEncryptionPassword = password
  183.  
  184.     'Create a DiskFolder object for the source folder
  185.     Dim source As New DiskFolder(sourceFolder)
  186.  
  187.     'Copy the contents of the source folder to the zip file
  188.     source.CopyFilesTo(m_events, "Zipping", zip, recursive, True, fileMask)
  189.   End Sub
  190.  
  191.   'Remove files from the zip file.
  192.   '
  193.   'zipFilename is the name of the zip file. The file MUST exist.
  194.   'fileMask is the name of the file to remove from the zip file. It can contain wildcards.
  195.   'recursive specifies if the files in the subfolders of zipFilename should also be removed.
  196.   Public Sub RemoveFilesFromZip(ByVal zipFilename As String, ByVal fileMask As String, ByVal recursive As Boolean)
  197.  
  198.     If (fileMask.Length = 0) Then
  199.       Throw New ArgumentException("You must specify file to remove from the zip file.", "fileMask")
  200.     End If
  201.  
  202.     'Create a DiskFile object for the specified filename
  203.     Dim zipFile As New DiskFile(zipFilename)
  204.  
  205.     If Not zipFile.Exists Then
  206.       Console.WriteLine("The specified zip file does not exist.")
  207.       Return
  208.     End If
  209.  
  210.     Console.WriteLine("Removing files matching the mask {0} from {1}...", fileMask, zipFilename)
  211.     Console.WriteLine()
  212.  
  213.     'Create a ZipArchive object to acces the zip file
  214.     Dim zip As New ZipArchive(zipFile)
  215.  
  216.     'Obtain a flat array of files to remove
  217.     Dim filesToRemove() As AbstractFile = zip.GetFiles(recursive, fileMask)
  218.  
  219.     'To avoid updating the physical zip file each time a file is removed, 
  220.     'we call BeginUpdate/EndUpdate on the zip archive
  221.     zip.BeginUpdate()
  222.  
  223.     Try
  224.       'Iterate on the returned array of AbstractFile objects and delete each file
  225.       Dim file As AbstractFile
  226.       For Each file In filesToRemove
  227.         Console.WriteLine("Removing {0}...", file.FullName)
  228.         file.Delete()
  229.       Next
  230.     Finally
  231.       zip.EndUpdate()
  232.     End Try
  233.   End Sub
  234.  
  235. #End Region
  236.  
  237. #Region " Zip event handlers "
  238.  
  239.   'Handles the ItemProgression event.
  240.   '
  241.   'sender is the object the raised this event.
  242.   'e is the data related to this event.
  243.   Public Sub m_events_ItemProgression(ByVal sender As Object, ByVal e As Xceed.FileSystem.ItemProgressionEventArgs) Handles m_events.ItemProgression
  244.     If Not e.CurrentItem Is Nothing Then
  245.       m_RetryCounter = 0
  246.       Console.WriteLine("{0} {1}...", e.UserData, e.CurrentItem.FullName)
  247.     End If
  248.   End Sub
  249.  
  250.   Public Sub m_events_ItemException(ByVal sender As Object, ByVal e As Xceed.FileSystem.ItemExceptionEventArgs) Handles m_events.ItemException
  251.     If (TypeOf (e.CurrentItem) Is ZippedFile) Then
  252.       If (TypeOf (e.Exception) Is InvalidDecryptionPasswordException) Then
  253.         If (m_RetryCounter < 3) Then
  254.  
  255.           Console.Write("Enter the password for the file {0}: ", e.CurrentItem.Name)
  256.  
  257.           Dim archive As ZipArchive = e.CurrentItem.RootFolder
  258.           archive.DefaultDecryptionPassword = Console.ReadLine()
  259.  
  260.           e.Action = ItemExceptionAction.Retry
  261.           m_RetryCounter = m_RetryCounter + 1
  262.         Else
  263.           Console.WriteLine("{0} has been skipped due to an invalid password", e.CurrentItem.Name)
  264.           e.Action = ItemExceptionAction.Ignore
  265.         End If
  266.       End If
  267.     End If
  268.  
  269.   End Sub
  270. #End Region
  271.  
  272. #Region " Entry-point and non-zip related methods "
  273.   Sub Main()
  274.     Try
  275.       Console.WriteLine()
  276.       Console.WriteLine("Xceed Zip for .NET - VB.NET ZipDemo Application")
  277.       Console.WriteLine("===============================================")
  278.       Console.WriteLine()
  279.  
  280.       Dim args() As String = GetCommandLineArgs()
  281.  
  282.       If (args.Length < 2) Then
  283.         PrintUsage()
  284.         Return
  285.       End If
  286.  
  287.       Select Case args(0)
  288.         Case "-l"
  289.           If (args.Length >= 3) Then
  290.             ListZip(args(1), args(2))
  291.           Else
  292.             ListZip(args(1), "")
  293.           End If
  294.         Case "-lf"
  295.           If (args.Length >= 3) Then
  296.             ListZipByFolder(args(1), args(2))
  297.           Else
  298.             ListZipByFolder(args(1), "")
  299.           End If
  300.         Case "-x"
  301.           Select Case args.Length()
  302.             Case 0 To 2
  303.               PrintUsage()
  304.  
  305.             Case 3
  306.               ExtractZip(args(1), args(2), "", "")
  307.  
  308.             Case 4
  309.               If (args(3).StartsWith("-p:")) Then
  310.                 ExtractZip(args(1), args(2), "", args(3).Substring(3))
  311.               Else
  312.                 ExtractZip(args(1), args(2), args(3), "")
  313.               End If
  314.  
  315.             Case Else
  316.               If Not (args(4).StartsWith("-p:")) Then
  317.                 PrintUsage()
  318.               Else
  319.                 ExtractZip(args(1), args(2), args(3), args(4).Substring(3))
  320.               End If
  321.           End Select
  322.  
  323.         Case "-a"
  324.           Select Case args.Length()
  325.             Case 0 To 3
  326.               PrintUsage()
  327.  
  328.             Case 4
  329.               AddFilesToZip(args(1), args(2), args(3), False, "")
  330.  
  331.             Case 5
  332.               If (args(4) = "-r") Then
  333.                 AddFilesToZip(args(1), args(2), args(3), True, "")
  334.               ElseIf (args(4).StartsWith("-p:")) Then
  335.                 AddFilesToZip(args(1), args(2), args(3), False, args(4).Substring(3))
  336.               Else
  337.                 PrintUsage()
  338.               End If
  339.  
  340.             Case Else
  341.               If ((args(4) = "-r") And (args(5).StartsWith("-p:"))) Then
  342.                 AddFilesToZip(args(1), args(2), args(3), True, args(5).Substring(3))
  343.               Else
  344.                 PrintUsage()
  345.               End If
  346.           End Select
  347.  
  348.         Case "-d"
  349.           If (args.Length < 3) Then
  350.             PrintUsage()
  351.           Else
  352.             Dim recurse As Boolean = False
  353.             If (args.Length >= 4) Then
  354.               recurse = (args(3) = "-r")
  355.             End If
  356.             RemoveFilesFromZip(args(1), args(2), recurse)
  357.           End If
  358.  
  359.         Case Else
  360.           PrintUsage()
  361.       End Select
  362.  
  363.     Catch except As Exception
  364.       Console.WriteLine()
  365.       Console.WriteLine("ERROR: The following exception occured:")
  366.       Console.WriteLine(except.ToString())
  367.       Console.WriteLine()
  368.     End Try
  369.     Console.WriteLine("Done!")
  370.   End Sub
  371.  
  372.   'Displays usage guidelines for the command-line application.
  373.   Private Sub PrintUsage()
  374.     Console.WriteLine("Usage:")
  375.     Console.WriteLine()
  376.     Console.WriteLine("  zipdemovb.exe -l filename.zip [filemask]")
  377.     Console.WriteLine("  -----------------------------")
  378.     Console.WriteLine("     Lists the contents of filename.zip filtered by the optional filemask")
  379.     Console.WriteLine()
  380.     Console.WriteLine("  zipdemovb.exe -lf filename.zip [filemask]")
  381.     Console.WriteLine("  -----------------------------")
  382.     Console.WriteLine("     Lists the contents of filename.zip by folders, filtered by the optional filemask")
  383.     Console.WriteLine()
  384.     Console.WriteLine("  zipdemovb.exe -x filename.zip destFolder [filemask] [-p:password]")
  385.     Console.WriteLine("  -----------------------------")
  386.     Console.WriteLine("     Extracts the contents of filename.zip to destFolder filtered by the optional filemask")
  387.     Console.WriteLine()
  388.     Console.WriteLine("  zipdemovb.exe -a filename.zip sourceFolder sourceFileMask [-r] [-p:password]")
  389.     Console.WriteLine("  -----------------------------")
  390.     Console.WriteLine("     Adds the contents of sourceFolder and sourceFileMask to filename.zip")
  391.     Console.WriteLine("     - If filename.zip does not exist, a new file is created. If it exists, it is updated.")
  392.     Console.WriteLine("     - If -r is specified, the files from the subfolders for sourceFolder are added")
  393.     Console.WriteLine()
  394.     Console.WriteLine("  zipdemovb.exe -d filename.zip fileMask [-r]")
  395.     Console.WriteLine("  -----------------------------")
  396.     Console.WriteLine("     Removes fileMask from filename.zip. If -r is specified, files will also be removed from the subfolders")
  397.     Console.WriteLine()
  398.   End Sub
  399.  
  400.   'Get the command-line arguments in a function that returns 
  401.   'them in an object containing an array.
  402.   Function GetCommandLineArgs() As String()
  403.     Dim commandLine As String = Microsoft.VisualBasic.Command()
  404.     Dim argument As String
  405.     Dim stringOpened As Boolean = False
  406.     Dim I As Long
  407.     Dim args(0) As String
  408.  
  409.     argument = ""
  410.     For I = 0 To commandLine.Length - 1
  411.       If commandLine.Chars(I) = " " And Not stringOpened Then
  412.         If argument.Length > 0 Then
  413.           ReDim Preserve args(UBound(args) + 1)
  414.           args(UBound(args) - 1) = argument.ToString()
  415.           argument = ""
  416.         End If
  417.       Else
  418.         If commandLine.Chars(I) = """" Then
  419.           stringOpened = Not stringOpened
  420.         Else
  421.           argument = argument & commandLine.Chars(I)
  422.         End If
  423.       End If
  424.     Next
  425.  
  426.     If (argument.Length > 0) Then
  427.       ReDim Preserve args(UBound(args) + 1)
  428.       args(UBound(args) - 1) = argument.ToString()
  429.     End If
  430.  
  431.     If UBound(args) > 1 Then
  432.       ReDim Preserve args(UBound(args) - 1)
  433.     End If
  434.  
  435.     Return args
  436.   End Function
  437. #End Region
  438.  
  439. #Region " Private Fields "
  440.   Private m_RetryCounter As Integer = 0
  441. #End Region
  442.  
  443.  
  444. End Module
  445.