public int Run()
        {
            //System.Diagnostics.Debugger.Break();

            List <String> itemsExtracted = new List <String>();

            global::Ionic.Zip.ExtractExistingFileAction WantOverwrite =
                (Ionic.Zip.ExtractExistingFileAction)Overwrite;

            // There way this works:  the EXE is a ZIP file.  So
            // read from the location of the assembly, in other words the path to the exe.
            Assembly a = Assembly.GetExecutingAssembly();

            int rc = 0;

            try
            {
                // workitem 7067
                using (global::Ionic.Zip.ZipFile zip = global::Ionic.Zip.ZipFile.Read(a.Location))
                {
                    if (!ListOnly)
                    {
                        if (Verbose)
                        {
                            System.Console.Write("Extracting to {0}", TargetDirectory);
                            System.Console.WriteLine(" (Existing file action: {0})", WantOverwrite.ToString());
                        }
                    }

                    bool header = true;
                    foreach (global::Ionic.Zip.ZipEntry entry in zip)
                    {
                        if (ListOnly || ReallyVerbose)
                        {
                            if (header)
                            {
                                System.Console.WriteLine("Extracting Zip file: {0}", zip.Name);
                                if ((zip.Comment != null) && (zip.Comment != ""))
                                {
                                    System.Console.WriteLine("Comment: {0}", zip.Comment);
                                }

                                System.Console.WriteLine("\n{1,-22} {2,9}  {3,5}   {4,9}  {5,3} {6,8} {0}",
                                                         "Filename", "Modified", "Size", "Ratio", "Packed", "pw?", "CRC");
                                System.Console.WriteLine(new System.String('-', 80));
                                header = false;
                            }

                            System.Console.WriteLine("{1,-22} {2,9} {3,5:F0}%   {4,9}  {5,3} {6:X8} {0}",
                                                     entry.FileName,
                                                     entry.LastModified.ToString("yyyy-MM-dd HH:mm:ss"),
                                                     entry.UncompressedSize,
                                                     entry.CompressionRatio,
                                                     entry.CompressedSize,
                                                     (entry.UsesEncryption) ? "Y" : "N",
                                                     entry.Crc);
                        }

                        if (!ListOnly)
                        {
                            if (Verbose && !ReallyVerbose)
                            {
                                System.Console.WriteLine("  {0}", entry.FileName);
                            }

                            if (entry.Encryption == global::Ionic.Zip.EncryptionAlgorithm.None)
                            {
                                try
                                {
                                    entry.Extract(TargetDirectory, WantOverwrite);
                                    itemsExtracted.Add(entry.FileName);
                                }
                                catch (Exception ex1)
                                {
                                    Console.WriteLine("  Error -- {0}", ex1.Message);
                                    rc++;
                                }
                            }
                            else
                            {
                                if (Password == null)
                                {
                                    Console.WriteLine("Cannot extract entry {0} without a password.", entry.FileName);
                                    rc++;
                                }
                                else
                                {
                                    try
                                    {
                                        entry.ExtractWithPassword(TargetDirectory, WantOverwrite, Password);
                                        itemsExtracted.Add(entry.FileName);
                                    }
                                    catch (Exception ex2)
                                    {
                                        Console.WriteLine("  Error -- {0}", ex2.Message);
                                        rc++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                Console.WriteLine("The self-extracting zip file is corrupted.");
                return(4);
            }

            if (rc != 0)
            {
                return(rc);
            }


            // potentially execute the embedded command
            if (PostUnpackCmdLineIsSet() && !SkipPostUnpackCommand)
            {
                if (ListOnly)
                {
                    Console.WriteLine("\nExecute on unpack: {0}", PostUnpackCmdLine);
                }
                else
                {
                    try
                    {
                        string[] args = SplitCommandLine(PostUnpackCmdLine);

                        if (args != null && args.Length > 0)
                        {
                            if (Verbose)
                            {
                                System.Console.WriteLine("Running command:  {0}", PostUnpackCmdLine);
                            }

                            ProcessStartInfo startInfo = new ProcessStartInfo(args[0]);
                            startInfo.WorkingDirectory = TargetDirectory;
                            startInfo.CreateNoWindow   = true;
                            if (args.Length > 1)
                            {
                                startInfo.Arguments = args[1];
                            }

                            using (Process p = Process.Start(startInfo))
                            {
                                if (p != null)
                                {
                                    p.WaitForExit();
                                    rc = p.ExitCode;
                                    // workitem 8925
                                    if (p.ExitCode == 0)
                                    {
                                        if (RemoveFilesAfterExe)
                                        {
                                            foreach (string s in itemsExtracted)
                                            {
                                                string fullPath = Path.Combine(TargetDirectory, s);
                                                try
                                                {
                                                    if (File.Exists(fullPath))
                                                    {
                                                        File.Delete(fullPath);
                                                    }
                                                    else if (Directory.Exists(fullPath))
                                                    {
                                                        Directory.Delete(fullPath, true);
                                                    }
                                                }
                                                catch
                                                {
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception exc1)
                    {
                        System.Console.WriteLine("{0}", exc1);
                        rc = 5;
                    }
                }
            }

            return(rc);
        }
Exemplo n.º 2
0
        private void DoExtract(Object obj)
        {
            List <string> itemsExtracted  = new List <String>();
            string        targetDirectory = txtExtractDirectory.Text;

            global::Ionic.Zip.ExtractExistingFileAction WantOverwrite = (Ionic.Zip.ExtractExistingFileAction)Overwrite;
            bool extractCancelled = false;

            System.Collections.Generic.List <String> didNotOverwrite =
                new System.Collections.Generic.List <String>();
            _setCancel = false;
            string currentPassword = "";

            SetProgressBars();

            try
            {
                // zip has already been set, when opening the exe.

                zip.ExtractProgress += ExtractProgress;
                foreach (global::Ionic.Zip.ZipEntry entry in zip)
                {
                    if (_setCancel)
                    {
                        extractCancelled = true; break;
                    }
                    if (entry.Encryption == global::Ionic.Zip.EncryptionAlgorithm.None)
                    {
                        try
                        {
                            entry.Extract(targetDirectory, WantOverwrite);
                            entryCount++;
                            itemsExtracted.Add(entry.FileName);
                        }
                        catch (Exception ex1)
                        {
                            if (WantOverwrite != global::Ionic.Zip.ExtractExistingFileAction.OverwriteSilently &&
                                ex1.Message.Contains("already exists."))
                            {
                                // The file exists, but the user did not ask for overwrite.
                                didNotOverwrite.Add("    " + entry.FileName);
                            }
                            else if (WantOverwrite == global::Ionic.Zip.ExtractExistingFileAction.OverwriteSilently ||
                                     ex1.Message.Contains("already exists."))
                            {
                                DialogResult result = MessageBox.Show(String.Format("Failed to extract entry {0} -- {1}", entry.FileName, ex1.Message),
                                                                      String.Format("Error Extracting {0}", entry.FileName), MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);

                                if (result == DialogResult.Cancel)
                                {
                                    _setCancel = true;
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        bool done = false;
                        while (!done)
                        {
                            if (currentPassword == "")
                            {
                                string t = PromptForPassword(entry.FileName);
                                if (t == "")
                                {
                                    done = true; // escape ExtractWithPassword loop
                                    continue;
                                }
                                currentPassword = t;
                            }

                            if (currentPassword == null) // cancel all
                            {
                                _setCancel      = true;
                                currentPassword = "";
                                break;
                            }

                            try
                            {
                                entry.ExtractWithPassword(targetDirectory, WantOverwrite, currentPassword);
                                entryCount++;
                                itemsExtracted.Add(entry.FileName);
                                done = true;
                            }
                            catch (Exception ex2)
                            {
                                // Retry here in the case of bad password.
                                if (ex2 as Ionic.Zip.BadPasswordException != null)
                                {
                                    currentPassword = "";
                                    continue; // loop around, ask for password again
                                }
                                else if (WantOverwrite != global::Ionic.Zip.ExtractExistingFileAction.OverwriteSilently &&
                                         ex2.Message.Contains("already exists."))
                                {
                                    // The file exists, but the user did not ask for overwrite.
                                    didNotOverwrite.Add("    " + entry.FileName);
                                    done = true;
                                }
                                else if (WantOverwrite == global::Ionic.Zip.ExtractExistingFileAction.OverwriteSilently &&
                                         !ex2.Message.Contains("already exists."))
                                {
                                    DialogResult result = MessageBox.Show(String.Format("Failed to extract the password-encrypted entry {0} -- {1}", entry.FileName, ex2.Message.ToString()),
                                                                          String.Format("Error Extracting {0}", entry.FileName), MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);

                                    done = true;
                                    if (result == DialogResult.Cancel)
                                    {
                                        _setCancel = true;
                                        break;
                                    }
                                }
                            } // catch
                        }     // while
                    }         // else (encryption)
                }             // foreach
            }
            catch (Exception)
            {
                MessageBox.Show("The self-extracting zip file is corrupted.",
                                "Error Extracting", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                Application.Exit();
            }


            // optionally provide a status report
            if (didNotOverwrite.Count > 0)
            {
                UnzipStatusReport f = new UnzipStatusReport();
                if (didNotOverwrite.Count == 1)
                {
                    f.Header = "This file was not extracted because the target file already exists:";
                }
                else
                {
                    f.Header = String.Format("These {0} files were not extracted because the target files already exist:",
                                             didNotOverwrite.Count);
                }
                f.Message = String.Join("\r\n", didNotOverwrite.ToArray());
                f.ShowDialog();
            }

            SetUiDone();

            if (extractCancelled)
            {
                return;
            }


            // optionally open explorer
            if (chk_OpenExplorer.Checked)
            {
                string w = System.Environment.GetEnvironmentVariable("WINDIR");
                if (w == null)
                {
                    w = "c:\\windows";
                }
                try
                {
                    Process.Start(Path.Combine(w, "explorer.exe"), targetDirectory);
                }
                catch { }
            }


            // optionally execute a command
            postUpackExeDone = new ManualResetEvent(false);
            if (this.chk_ExeAfterUnpack.Checked && PostUnpackCmdLineIsSet())
            {
                try
                {
                    string[] cmd = SplitCommandLine(txtPostUnpackCmdLine.Text);
                    if (cmd != null && cmd.Length > 0)
                    {
                        object[] args = { cmd,
                                          this.chk_Remove.Checked,
                                          itemsExtracted,
                                          targetDirectory };
                        ThreadPool.QueueUserWorkItem(new WaitCallback(StartPostUnpackProc), args);
                    }
                    else
                    {
                        postUpackExeDone.Set();
                    }

                    // else, nothing.
                }
                catch { postUpackExeDone.Set(); }
            }
            else
            {
                postUpackExeDone.Set();
            }

            // quit if this is non-interactive
            if (!Interactive)
            {
                postUpackExeDone.WaitOne();
                Application.Exit();
            }
        }
        public int Run()
        {
            //System.Diagnostics.Debugger.Break();

            global::Ionic.Zip.ExtractExistingFileAction WantOverwrite =
                (overwriteOption == 0) ?
                global::Ionic.Zip.ExtractExistingFileAction.Throw // default
            :
                (overwriteOption == 1) ?
                global::Ionic.Zip.ExtractExistingFileAction.OverwriteSilently
            :
                (overwriteOption == 2) ?
                global::Ionic.Zip.ExtractExistingFileAction.DoNotOverwrite
            :
                global::Ionic.Zip.ExtractExistingFileAction.Throw;// default


            // There way this works:  the EXE is a ZIP file.  So
            // read from the location of the assembly, in other words the path to the exe.
            Assembly a = Assembly.GetExecutingAssembly();

            int rc = 0;

            try
            {
                // workitem 7067
                using (global::Ionic.Zip.ZipFile zip = global::Ionic.Zip.ZipFile.Read(a.Location))
                {
                    bool header = true;
                    foreach (global::Ionic.Zip.ZipEntry entry in zip)
                    {
                        if (ListOnly || Verbose)
                        {
                            if (header)
                            {
                                System.Console.WriteLine("Extracting Zip file: {0}", zip.Name);
                                if ((zip.Comment != null) && (zip.Comment != ""))
                                {
                                    System.Console.WriteLine("Comment: {0}", zip.Comment);
                                }

                                System.Console.WriteLine("\n{1,-22} {2,9}  {3,5}   {4,9}  {5,3} {6,8} {0}",
                                                         "Filename", "Modified", "Size", "Ratio", "Packed", "pw?", "CRC");
                                System.Console.WriteLine(new System.String('-', 80));
                                header = false;
                            }

                            System.Console.WriteLine("{1,-22} {2,9} {3,5:F0}%   {4,9}  {5,3} {6:X8} {0}",
                                                     entry.FileName,
                                                     entry.LastModified.ToString("yyyy-MM-dd HH:mm:ss"),
                                                     entry.UncompressedSize,
                                                     entry.CompressionRatio,
                                                     entry.CompressedSize,
                                                     (entry.UsesEncryption) ? "Y" : "N",
                                                     entry.Crc);
                        }

                        if (!ListOnly)
                        {
                            if (entry.Encryption == global::Ionic.Zip.EncryptionAlgorithm.None)
                            {
                                try
                                {
                                    entry.Extract(TargetDirectory, WantOverwrite);
                                }
                                catch (Exception ex1)
                                {
                                    Console.WriteLine("Failed to extract entry {0} -- {1}", entry.FileName, ex1.Message);
                                    rc++;
                                    break;
                                }
                            }
                            else
                            {
                                if (Password == null)
                                {
                                    Console.WriteLine("Cannot extract entry {0} without a password.", entry.FileName);
                                }
                                else
                                {
                                    try
                                    {
                                        entry.ExtractWithPassword(TargetDirectory, WantOverwrite, Password);
                                    }
                                    catch (Exception ex2)
                                    {
                                        // probably want a retry here in the case of bad password.
                                        Console.WriteLine("Failed to extract entry {0} -- {1}", entry.FileName, ex2.Message);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                Console.WriteLine("The self-extracting zip file is corrupted.");
                return(4);
            }

            if (rc != 0)
            {
                return(rc);
            }

            // potentially execute the embedded command
            if (PostUnpackCmdLineIsSet())
            {
                if (ListOnly)
                {
                    Console.WriteLine("\nExecute on unpack: {0}", PostUnpackCmdLine);
                }
                else
                {
                    try
                    {
                        string[] args = PostUnpackCmdLine.Split(new char[] { ' ' }, 2);

                        Directory.SetCurrentDirectory(TargetDirectory);
                        System.Diagnostics.Process p = null;
                        if (args.Length > 1)
                        {
                            p = System.Diagnostics.Process.Start(args[0], args[1]);
                        }

                        else if (args.Length == 1)
                        {
                            p = System.Diagnostics.Process.Start(args[0]);
                        }
                        // else, nothing.

                        if (p != null)
                        {
                            p.WaitForExit();
                            rc = p.ExitCode;
                        }
                    }
                    catch
                    {
                        rc = 5;
                    }
                }
            }

            return(rc);
        }