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

  1. /*
  2.  * Xceed Zip for .NET - ZipDemo Sample Application
  3.  * Copyright (c) 2000-2002 - Xceed Software Inc.
  4.  * 
  5.  * [ZipDemo.cs]
  6.  * 
  7.  * This console application demonstrates how to perform basic zip file manipulation.
  8.  * 
  9.  * This file is part of Xceed Zip for .NET. The source code in this file 
  10.  * is only intended as a supplement to the documentation, and is provided
  11.  * "as is", without warranty of any kind, either expressed or implied.
  12.  */
  13.  
  14. using System;
  15. using System.IO;
  16. using Xceed.FileSystem;
  17. using Xceed.Zip;
  18.  
  19. namespace Xceed.Zip.Samples.ZipDemo
  20. {
  21.   /// <summary>
  22.   /// Demonstrates how to perform basic zip file manipulation.
  23.   /// </summary>
  24.   public class ZipDemo
  25.   {
  26.     #region Zipfile listing methods
  27.  
  28.     /// <summary>
  29.     /// Lists the contents of a zip file based on a file mask (wildcard), and displays
  30.     /// the results as a non-formatted list on the console.
  31.     /// </summary>
  32.     /// <param name="zipFilename">Name of the zip file. The file must exist.</param>
  33.     /// <param name="fileMask">Wildcard for filtering the list output.</param>
  34.     public static void ListZip( string zipFilename, string fileMask )
  35.     {
  36.       // Create a DiskFile object for the specified zip filename
  37.  
  38.       DiskFile zipFile = new DiskFile( zipFilename );
  39.  
  40.       if( !zipFile.Exists )
  41.       {
  42.         Console.WriteLine( "The specified zip file does not exist." );
  43.         return;
  44.       }
  45.  
  46.       Console.WriteLine( "Listing all files matching the mask \"{0}\" contained in {1}...", fileMask, zipFilename );
  47.       Console.WriteLine();
  48.  
  49.       // Create a ZipArchive object to access the zipfile.
  50.  
  51.       ZipArchive zip = new ZipArchive( zipFile );
  52.  
  53.       // Obtain a flat array of all the files contained in the zip file and its subfolders.
  54.  
  55.       AbstractFile[] files = zip.GetFiles( true, fileMask );
  56.       
  57.       // Iterate on the returned array of AbstractFile objects, and print the full name
  58.       // of each file.
  59.  
  60.       foreach( AbstractFile file in files )
  61.         Console.WriteLine( file.FullName );
  62.  
  63.       Console.WriteLine();
  64.  
  65.       if( files.Length == 0 )
  66.         Console.WriteLine( "The zipfile is empty, or it does not contain any file matching the specified mask." );
  67.       else
  68.         Console.WriteLine( "{0} files.", files.Length );
  69.     }
  70.  
  71.     /// <summary>
  72.     /// Lists the contents of a zip file based on a file mask (wildcard), and displays
  73.     /// the results folder by folder.
  74.     /// </summary>
  75.     /// <param name="zipFilename">Name of the zip file. The file must exist.</param>
  76.     /// <param name="fileMask">Wildcard for filtering the list output.</param>
  77.     public static void ListZipByFolder( string zipFilename, string fileMask )
  78.     {
  79.       // Create a DiskFile object for the specified zip filename
  80.  
  81.       DiskFile zipFile = new DiskFile( zipFilename );
  82.  
  83.       if( !zipFile.Exists )
  84.       {
  85.         Console.WriteLine( "The specified zip file does not exist." );
  86.         return;
  87.       }
  88.  
  89.       Console.WriteLine( "Listing all files matching the mask \"{0}\" contained in {1}, folder by folder...", fileMask, zipFilename );
  90.       Console.WriteLine();
  91.  
  92.       // Create a ZipArchive object to access the zipfile.
  93.  
  94.       ZipArchive zip = new ZipArchive( zipFile );
  95.  
  96.       // Since the ZipArchive class derives from ZippedFolded, which derives from
  97.       // AbstractFolder, we can directly call a utility method that lists the contents
  98.       // of an AbstractFolder object recursively.
  99.  
  100.       ListFolder( zip, fileMask );
  101.     }
  102.  
  103.     /// <summary>
  104.     /// Utility method that lists the contents of one folder in a zip file, and calls
  105.     /// itself recursively for subfolders.
  106.     /// </summary>
  107.     /// <param name="folder">Folder that must be listed.</param>
  108.     /// <param name="fileMask">File Mask used for filtering.</param>
  109.     private static void ListFolder( AbstractFolder folder, string fileMask )
  110.     {
  111.       Console.WriteLine();
  112.       Console.WriteLine( "Listing of " + folder.FullName );
  113.       Console.WriteLine();
  114.  
  115.       // Obtain an array of files contained in the current folder.
  116.  
  117.       AbstractFile[] files = folder.GetFiles( false, fileMask );
  118.  
  119.       // Iterate on the returned array of AbstractFile objects, and print the details
  120.       // of each file.
  121.  
  122.       foreach( AbstractFile file in files )
  123.       {
  124.         Console.WriteLine( 
  125.           "{0}\t{1}\t{2}\t{3}", 
  126.           file.LastWriteDateTime.ToShortDateString(), 
  127.           file.LastWriteDateTime.ToShortTimeString(),  
  128.           file.Size,
  129.           file.Name );
  130.       }
  131.  
  132.       Console.WriteLine();
  133.       Console.WriteLine( "{0} files.", files.Length );
  134.  
  135.       // Call ListFolder recursively for the subfolders of the current folder.
  136.       
  137.       foreach( AbstractFolder subFolder in folder.GetFolders( false ) )
  138.         ListFolder( subFolder, fileMask );
  139.     }
  140.  
  141.     #endregion
  142.  
  143.     #region Zipfile extraction methods
  144.  
  145.     /// <summary>
  146.     /// Extracts the contents of a zip file to a specified folder, based on a file mask (wildcard).
  147.     /// </summary>
  148.     /// <param name="zipFilename">Name of the zip file. The file must exist.</param>
  149.     /// <param name="destFolder">Folder into which the files should be extracted.</param>
  150.     /// <param name="fileMask">Wildcard for filtering the files to be extracted.</param>
  151.     public static void ExtractZip( string zipFilename, string destFolder, string fileMask, string password )
  152.     {
  153.       // Create a DiskFile object for the specified zip filename
  154.  
  155.       DiskFile zipFile = new DiskFile( zipFilename );
  156.  
  157.       if( !zipFile.Exists )
  158.       {
  159.         Console.WriteLine( "The specified zip file does not exist." );
  160.         return;
  161.       }
  162.  
  163.       Console.WriteLine( "Extracting all files matching the mask \"{0}\" to \"{1}\"...", fileMask, destFolder );
  164.       Console.WriteLine();
  165.  
  166.       // Create a ZipArchive object to access the zipfile.
  167.  
  168.       ZipArchive zip = new ZipArchive( zipFile );
  169.       zip.DefaultDecryptionPassword = password;
  170.  
  171.       // Create a DiskFolder object for the destination folder
  172.  
  173.       DiskFolder destinationFolder = new DiskFolder( destFolder );
  174.  
  175.       // Create a FileSystemEvents object for handling the ItemProgression event
  176.  
  177.       FileSystemEvents events = new FileSystemEvents();
  178.  
  179.       // Subscribe to the ItemProgression event
  180.  
  181.       events.ItemProgression += new ItemProgressionEventHandler( OnItemProgression );
  182.       events.ItemException += new ItemExceptionEventHandler( OnItemException );
  183.  
  184.       // Copy the contents of the zip to the destination folder.
  185.  
  186.       zip.CopyFilesTo( events, "Extracting", destinationFolder, true, true, fileMask );
  187.     }
  188.  
  189.     #endregion
  190.  
  191.     #region Zip update methods
  192.  
  193.     /// <summary>
  194.     /// Adds files to a zip file.
  195.     /// </summary>
  196.     /// <param name="zipFilename">Name of the zip file. If it does not exist, it will be created. If it exists, it will be updated.</param>
  197.     /// <param name="sourceFolder">Name of the folder from which to add files.</param>
  198.     /// <param name="fileMask">Name of the file to add to the zip file. Can include wildcards.</param>
  199.     /// <param name="recursive">Specifies if the files in the sub-folders of <paramref name="sourceFolder"/> should also be added.</param>
  200.     public static void AddFilesToZip( string zipFilename, string sourceFolder, string fileMask, bool recursive, string password )
  201.     {
  202.       if( sourceFolder.Length == 0 )
  203.         throw new ArgumentException( "You must specify a source folder from which files will be added to the zip file.", "sourceFolder" );
  204.       // Create a DiskFile object for the specified zip filename
  205.  
  206.       DiskFile zipFile = new DiskFile( zipFilename );
  207.  
  208.       // Check if the file exists
  209.  
  210.       if( !zipFile.Exists )
  211.       {
  212.         Console.WriteLine( "Creating a new zip file \"{0}\"...", zipFilename );
  213.         zipFile.Create();
  214.       }
  215.       else
  216.       {
  217.         Console.WriteLine( "Updating existing zip file \"{0}\"...", zipFilename );
  218.       }
  219.  
  220.       Console.WriteLine();
  221.  
  222.       // Create a ZipArchive object to access the zipfile.
  223.  
  224.       ZipArchive zip = new ZipArchive( zipFile );
  225.       zip.DefaultEncryptionPassword = password;
  226.  
  227.       // Create a DiskFolder object for the source folder
  228.  
  229.       DiskFolder source = new DiskFolder( sourceFolder );
  230.  
  231.       // Create a FileSystemEvents object for handling the ItemProgression event
  232.  
  233.       FileSystemEvents events = new FileSystemEvents();
  234.  
  235.       // Subscribe to the ItemProgression event
  236.  
  237.       events.ItemProgression += new ItemProgressionEventHandler( OnItemProgression );
  238.  
  239.       // Copy the contents of the zip to the destination folder.
  240.       source.CopyFilesTo( events, "Zipping", zip, recursive, true, fileMask );      
  241.     }
  242.  
  243.     /// <summary>
  244.     /// Removes files from a zip file.
  245.     /// </summary>
  246.     /// <param name="zipFilename">Name of the zip file. The file must exist.</param>
  247.     /// <param name="fileMask">Name of the file to remove from the zip file. Can contain wildcards.</param>
  248.     /// <param name="recursive">Specifies if the files in the sub-folders of <paramref name="zipFilename"/> should also be removed.</param>
  249.     public static void RemoveFilesFromZip( string zipFilename, string fileMask, bool recursive )
  250.     {
  251.       if( fileMask.Length == 0 )
  252.         throw new ArgumentException( "You must specify a file to remove from the zip file.", "fileMask" );
  253.  
  254.       // Create a DiskFile object for the specified zip filename
  255.  
  256.       DiskFile zipFile = new DiskFile( zipFilename );
  257.  
  258.       if( !zipFile.Exists )
  259.       {
  260.         Console.WriteLine( "The specified zip file does not exist." );
  261.         return;
  262.       }
  263.  
  264.       Console.WriteLine( "Removing files matching the mask \"{0}\" from \"{1}\"...", fileMask, zipFilename );
  265.       Console.WriteLine();
  266.  
  267.       // Create a ZipArchive object to access the zipfile.
  268.  
  269.       ZipArchive zip = new ZipArchive( zipFile );
  270.  
  271.       // Obtain a flat array of files to remove
  272.  
  273.       AbstractFile[] filesToRemove = zip.GetFiles( recursive, fileMask );
  274.  
  275.       // To avoid updating the physical zip file each time a single file is
  276.       // removed, we call BeginUpdate/EndUpdate on the zip archive.
  277.  
  278.       zip.BeginUpdate();
  279.  
  280.       try
  281.       {
  282.         // Iterate on the returned array of AbstractFile objects, and delete each file.
  283.  
  284.         foreach( AbstractFile file in filesToRemove )
  285.         {
  286.           Console.WriteLine( "Removing {0}...", file.FullName );
  287.           file.Delete();
  288.         }
  289.       }
  290.       finally
  291.       {
  292.         zip.EndUpdate();
  293.       }
  294.     }
  295.  
  296.     #endregion
  297.  
  298.     #region Zip events handlers
  299.  
  300.     /// <summary>
  301.     /// Handles the ItemProgression event.
  302.     /// </summary>
  303.     /// <param name="sender">The object that raised this event.</param>
  304.     /// <param name="e">Data related to this event.</param>
  305.     private static void OnItemProgression( object sender, ItemProgressionEventArgs e )
  306.     {
  307.       if( e.CurrentItem != null )
  308.       {
  309.         m_RetryCounter = 0;
  310.         Console.WriteLine( "{0} {1}...", ( string )e.UserData, e.CurrentItem.FullName );
  311.       }
  312.     }
  313.  
  314.  
  315.     private static void OnItemException( object sender, ItemExceptionEventArgs e )
  316.     {
  317.       if( e.CurrentItem is ZippedFile )
  318.       {
  319.         if( e.Exception is InvalidDecryptionPasswordException )
  320.         {
  321.           
  322.             if( m_RetryCounter < 3 )
  323.             {
  324.               Console.Write( "Enter the password for the file {0}: ", e.CurrentItem.Name );
  325.  
  326.               ( ( ZipArchive )e.CurrentItem.RootFolder ).DefaultDecryptionPassword = Console.ReadLine();          
  327.               e.Action = ItemExceptionAction.Retry;
  328.               m_RetryCounter++;
  329.             }
  330.             else
  331.             {
  332.               Console.WriteLine( "{0} has been skipped due to an invalid password", e.CurrentItem.Name );
  333.               e.Action = ItemExceptionAction.Ignore;
  334.             }
  335.           }
  336.       }
  337.     }
  338.  
  339.     #endregion
  340.  
  341.     #region Entry-point and non-zip related methods
  342.  
  343.     /// <summary>
  344.     /// Entry-point for the console application.
  345.     /// </summary>
  346.     /// <param name="args">Arguments supplied on the command line.</param>
  347.     public static void Main( string[] args )
  348.     {
  349.       try
  350.       {
  351.         Console.WriteLine();
  352.         Console.WriteLine( "Xceed Zip for .NET - ZipDemo" );
  353.         Console.WriteLine( "=================================" );
  354.         Console.WriteLine();
  355.  
  356.         if( args.Length < 2 )
  357.         {
  358.           PrintUsage();
  359.           return;
  360.         }
  361.  
  362.         switch( args[ 0 ] )
  363.         {
  364.           case "-l":
  365.             ListZip( args[ 1 ], args.Length >= 3 ? args[ 2 ] : "" );
  366.             break;
  367.  
  368.           case "-lf":
  369.             ListZipByFolder( args[ 1 ], args.Length >= 3 ? args[ 2 ] : "" );
  370.             break;
  371.  
  372.           case "-x":
  373.             switch( args.Length )
  374.             {
  375.               case 0:
  376.               case 1:
  377.               case 2:
  378.                 PrintUsage();
  379.                 break;
  380.  
  381.               case 3:
  382.                 ExtractZip( args[ 1 ], args[ 2 ], "", "" );
  383.                 break;
  384.  
  385.               case 4: 
  386.                 if( args[ 3 ].StartsWith( "-p:" ) )
  387.                   ExtractZip( args[ 1 ], args[ 2 ], "", args[ 3 ].Substring( 3 ) );
  388.                 else
  389.                   ExtractZip( args[ 1 ], args[ 2 ], args[ 3 ], "" );
  390.                 break;
  391.  
  392.               default:
  393.                 if ( !args[ 4 ].StartsWith( "-p:" ) )
  394.                 {
  395.                   PrintUsage();
  396.                 }
  397.                 else
  398.                   ExtractZip( args[ 1 ], args[ 2 ], args[ 3 ], args[ 4 ].Substring( 3 ) );
  399.                 break;
  400.             }
  401.               
  402.             break;
  403.  
  404.           case "-a":
  405.             switch( args.Length )
  406.             {
  407.               case 0:
  408.               case 1:
  409.               case 2:
  410.               case 3:
  411.                 PrintUsage();
  412.                 break;
  413.  
  414.               case 4:
  415.                 AddFilesToZip( args[ 1 ], args[ 2 ], args[ 3 ], false, "" );
  416.                 break;
  417.  
  418.               case 5:
  419.                 if( args[ 4 ] == "-r" )
  420.                   AddFilesToZip( args[ 1 ], args[ 2 ], args[ 3 ], true, "" );
  421.                 else if( args[ 4 ].StartsWith( "-p:" ) )
  422.                   AddFilesToZip( args[ 1 ], args[ 2 ], args[ 3 ], false, args[ 4 ].Substring( 3 ) );
  423.                 else
  424.                   PrintUsage();
  425.  
  426.                 break;
  427.  
  428.               default:
  429.                 if( args[ 4 ] == "-r" && args[ 5 ].StartsWith( "-p:" ))
  430.                   AddFilesToZip( args[ 1 ], args[ 2 ], args[ 3 ], true, args[ 5 ].Substring( 3 ) );
  431.                 else
  432.                   PrintUsage();
  433.  
  434.                 break;
  435.             }
  436.             break;
  437.  
  438.           case "-d":
  439.             if( args.Length < 3 )
  440.               PrintUsage();
  441.             else
  442.               RemoveFilesFromZip( args[ 1 ], args[ 2 ], args.Length >= 4 && args[ 3 ] == "-r" );
  443.  
  444.             break;
  445.  
  446.           default:
  447.             PrintUsage();
  448.             break;
  449.         }
  450.       }
  451.       catch( Exception except )
  452.       {
  453.         Console.WriteLine();
  454.         Console.WriteLine( "ERROR: The following exception occured:" );
  455.         Console.WriteLine( except.Message );
  456.         Console.WriteLine();
  457.       }
  458.  
  459.       Console.WriteLine( "Done!" );
  460.     }
  461.  
  462.     /// <summary>
  463.     /// Displays usage guidelines for the command-line application.
  464.     /// </summary>
  465.     private static void PrintUsage()
  466.     {
  467.       Console.WriteLine( "Usage:" );
  468.       Console.WriteLine();
  469.       Console.WriteLine( "  zipdemo.exe -l filename.zip [filemask]" );
  470.       Console.WriteLine( "  ---------------------------" );
  471.       Console.WriteLine( "    Lists the contents of filename.zip, filtered by the optional filemask." );
  472.       Console.WriteLine();
  473.       Console.WriteLine( "  zipdemo.exe -lf filename.zip [filemask]" );
  474.       Console.WriteLine( "  ---------------------------" );
  475.       Console.WriteLine( "    Lists the contents of filename.zip by folders, filtered by the optional filemask." );
  476.       Console.WriteLine();
  477.       Console.WriteLine( "  zipdemo.exe -x filename.zip destFolder [filemask] [-p:password]" );
  478.       Console.WriteLine( "  ---------------------------" );
  479.       Console.WriteLine( "    Extracts the contents of filename.zip to destFolder, filtered by the optional filemask." );
  480.       Console.WriteLine();
  481.       Console.WriteLine( "  zipdemo.exe -a filename.zip sourceFolder sourceFileMask [-r] [-p:password]" );
  482.       Console.WriteLine( "  ---------------------------" );
  483.       Console.WriteLine( "    Adds the contents of sourceFolder and sourceFileMask to zipfile.zip." );
  484.       Console.WriteLine( "    - If filename.zip does not exist, creates a new file. If it exists, it will be updated." );
  485.       Console.WriteLine( "    - If -r is specified, adds the files from sourceFolder's subfolders." );
  486.       Console.WriteLine();
  487.       Console.WriteLine( "  zipdemo.exe -d filename.zip fileMask [-r]" );
  488.       Console.WriteLine( "  ---------------------------" );
  489.       Console.WriteLine( "    Removes fileMask from filename.zip. If -r is specified, files will also be removed from subfolders." );
  490.       Console.WriteLine();
  491.     }
  492.  
  493.     #endregion
  494.  
  495.     #region Private Fields
  496.       private static int m_RetryCounter;     
  497.     #endregion
  498.  
  499.   }
  500. }
  501.  
  502.