Exemplo n.º 1
0
        void downloader_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            string[] us             = (string[])e.UserState;
            string   currentVersion = us[0];
            string   downloadToPath = us[1];
            string   executeTarget  = us[2];

            if (!downloadToPath.EndsWith("\\"))
            {
                downloadToPath += "\\";
            }

            // Download folder + zip file
            string zipName = downloadToPath + currentVersion + ".zip";
            // Download folder\version\ + executable
            string exePath = downloadToPath + currentVersion + "\\" + executeTarget;

            if (new FileInfo(zipName).Exists)
            {
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipName))
                {
                    if (TextVer == "app.version")
                    {
                        if (File.Exists(Environment.CurrentDirectory + "/Launcher.bak"))
                        {
                            File.Delete(Environment.CurrentDirectory + "/Launcher.bak");
                        }
                        File.Move(AppDomain.CurrentDomain.FriendlyName, "Launcher.bak");
                        Thread.Sleep(5000);
                        zip.ExtractAll(downloadToPath, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);

                        MessageBoxResult result = System.Windows.MessageBox.Show("Launcher updated, restart app!", "Congratulations", MessageBoxButton.OK, MessageBoxImage.Question);
                        if (result == MessageBoxResult.OK)
                        {
                            Process proc = Process.Start(downloadToPath + "\\" + executeTarget);
                            Environment.Exit(0);
                        }
                    }
                    else
                    {
                        zip.ExtractAll(downloadToPath + currentVersion, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                    }
                }
                if (new FileInfo(exePath).Exists)
                {
                    Versions.CreateLocalVersionFile(downloadToPath, TextVer, currentVersion);
                    Process proc = Process.Start(exePath);
                }
                else
                {
                    System.Windows.MessageBox.Show("Problem with download. File does not exist.");
                }
            }
            else
            {
                System.Windows.MessageBox.Show("Problem with download. File does not exist.");
            }
        }
Exemplo n.º 2
0
 private void button9_Click(object sender, EventArgs e)
 {
     if (File.Exists(Application.StartupPath + @"\Toolbox\XMB Modder\PS3_XMB_Modder.exe"))
     {
         this.WindowState = FormWindowState.Minimized;
         System.Diagnostics.Process.Start(Application.StartupPath + @"\Toolbox\XMB Modder\PS3_XMB_Modder.exe");
     }
     else
     {
         DialogResult result = MessageBox.Show("This File Needs To Be Downloaded First", "Continue?", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
         if (DialogResult.Yes == result && System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == true)
         {
             DownloadFile("http://www.xxxthedartkprogramerxxx.net/Download/XMB Modder.zip", Application.StartupPath + @"\Toolbox\XMB Modder.zip");
             this.notifyIcon1.ShowBalloonTip(0x7d0, "Extracting", "Extracting XMB Modder Please Wait", ToolTipIcon.Info);
             Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(Application.StartupPath + @"\Toolbox\XMB Modder.zip");
             zip.ExtractAll(Application.StartupPath + @"\Toolbox\");
             this.notifyIcon1.ShowBalloonTip(0x7d0, "Extracted", "Opening File", ToolTipIcon.Info);
             this.WindowState = FormWindowState.Minimized;
             System.Diagnostics.Process.Start(Application.StartupPath + @"\Toolbox\XMB Modder\PS3_XMB_Modder.exe");
             File.Delete(Application.StartupPath + @"\Toolbox\XMB Modder.zip");
         }
         else if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == false)
         {
             MessageBox.Show("You Need An Internet Connection For This");
         }
     }
 }
Exemplo n.º 3
0
        /// <summary>
        /// 解壓縮後刪除Zip檔
        /// </summary>
        /// <param name="fullPathDto"></param>
        /// <param name="zipPassword"></param>
        /// <returns></returns>
        public static bool UnZipAndDelete(FullPathDto fullPathDto, string zipPassword)
        {
            if (File.Exists(fullPathDto.LocalZipFullPath))
            {
                try
                {
                    var options = new ReadOptions {
                        StatusMessageWriter = System.Console.Out
                    };
                    using (Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(fullPathDto.LocalZipFullPath, options))
                    {
                        zip.Password = zipPassword;                                                           // 解壓密碼
                        zip.ExtractAll(fullPathDto.LocalFolder, ExtractExistingFileAction.OverwriteSilently); // 解壓全部
                    }
                    File.Delete(fullPathDto.LocalZipFullPath);
                    if (File.Exists(fullPathDto.LocalXmlFullPath))
                    {
                        Console.WriteLine($"解ZIP 成功 XML: {fullPathDto.LocalXmlFullPath}");
                        return(true);
                    }

                    return(false);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"解ZIP {fullPathDto.LocalZipFullPath} 發生錯誤 {ex}");
                }
            }

            return(false);
        }
Exemplo n.º 4
0
        private bool OpenZip(String path, out string outpath)
        {
            //ZipFileを作成する
            using (Ionic.Zip.ZipFile zip = ZipFile.Read(path, new ReadOptions()
            {
                Encoding = Encoding.GetEncoding("shift_jis")
            }))
            {
                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;

                zip.ExtractExistingFile = Ionic.Zip.ExtractExistingFileAction.OverwriteSilently;
                //エラーが出てもスキップする。デフォルトはThrow。
                zip.ZipErrorAction = Ionic.Zip.ZipErrorAction.Skip;

                zip.Password   = "******";
                zip.Encryption = Ionic.Zip.EncryptionAlgorithm.WinZipAes256;

                // Tempフォルダーに書き出し隔離
                string tempFolder = Path.GetTempPath() + Path.GetRandomFileName();
                Directory.CreateDirectory(tempFolder);

                //フォルダを追加する
                zip.ExtractAll(tempFolder);

                outpath = tempFolder;
            }

            return(true);
        }
Exemplo n.º 5
0
        private void ImportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFile = new OpenFileDialog();

            if (openFile.ShowDialog() == DialogResult.OK)
            {
                string codes_zip = openFile.FileName;

                try
                {
                    using (Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(codes_zip))
                    {
                        zip.Password = "******";

                        zip.ExtractAll("TEMP\\Codes", Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                    }
                } catch (Exception ex)
                {
                    if (ex.Message.ToLower().Contains("bad password"))
                    {
                        //Message box
                        Console.WriteLine("Wrong password");
                    }
                }

                CDT_Tab_Template.imported_CSV_offline = @"TEMP\Codes\offline.csv";
                CDT_Tab_Template.imported_CSV_update  = @"TEMP\Codes\update.csv";
            }
        }
Exemplo n.º 6
0
        private void convert_Click_1(object sender, EventArgs e)
        {
            DecryptFile(fileName, @"tc2.dat");
            using (Ionic.Zip.ZipFile zipnew = Ionic.Zip.ZipFile.Read(zipPath))
            {
                for (int i = 0; i < 100; i++)
                {
                    //Thread.Sleep(100);


                    foreach (ZipEntry zenew in zipnew)
                    {
                        //Ionic.Zip.ZipFile.ExtractToDirectory(zipPath, extractPath);
                        //zipnew.ExtractAll(extractPath, ExtractExistingFileAction.OverwriteSilently);
                        backgroundWorker1.ReportProgress(i);
                    }
                }
                //zip.ExtractAll(extractPath, ExtractExistingFileAction.OverwriteSilently);
                //System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, extractPath);
                //ZipFile.ExtractToDirectory(zipPath, extractPath);

                // Periodically report progress to the main thread so that it can
                // update the UI.  In most cases you'll just need to send an
                // integer that will update a ProgressBar

                zipnew.ExtractAll(extractPath, ExtractExistingFileAction.OverwriteSilently);


                backgroundWorker1.RunWorkerAsync();
                convert.Enabled        = false;
                kryptonButton1.Enabled = true;
            }
            System.IO.File.Delete(@"tc2.dat");
            string   inString  = Environment.GetEnvironmentVariable("ProgramFiles").ToLower();
            TextInfo cultInfo  = new CultureInfo("en-US", false).TextInfo;
            string   output    = cultInfo.ToTitleCase(inString);
            string   shortfold = output + @"\microsoft games\age of empires ii" + @"\";

            //Copy icon
            System.IO.File.Copy("icon.ico", shortfold + @"Age2_x1\icon.ico", true);
            //Create shortcut

            StringBuilder allUserProfile = new StringBuilder(260);

            SHGetSpecialFolderPath(IntPtr.Zero, allUserProfile, CSIDL_COMMON_DESKTOPDIRECTORY, false);

            string settingsLink = Path.Combine(allUserProfile.ToString(), "Age of Empires II The Conquerors.lnk");
            //Create All Users Desktop Shortcut for Application Settings
            WshShellClass shellClass = new WshShellClass();
            IWshShortcut  shortcut   = (IWshShortcut)shellClass.CreateShortcut(settingsLink);

            shortcut.TargetPath   = shortfold + @"Age2_x1\age2_x1.exe";
            shortcut.IconLocation = shortfold + @"Age2_x1\icon.ico";
            shortcut.Arguments    = "arg1 arg2";
            shortcut.Description  = "Age of Empires II The Conquerors";
            shortcut.Save();

            MessageBox.Show("Shortcut created on your Desktop!");
            progressBar1.Enabled = false;
        }
Exemplo n.º 7
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            using (Ionic.Zip.ZipFile zipnew = Ionic.Zip.ZipFile.Read(zipPath))
            {
                for (int i = 0; i < 100; i++)
                {
                    //Thread.Sleep(100);


                    foreach (ZipEntry zenew in zipnew)
                    {
                        //Ionic.Zip.ZipFile.ExtractToDirectory(zipPath, extractPath);
                        //zipnew.ExtractAll(extractPath, ExtractExistingFileAction.OverwriteSilently);
                        backgroundWorker1.ReportProgress(i);
                    }
                }
                //zip.ExtractAll(extractPath, ExtractExistingFileAction.OverwriteSilently);
                //System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, extractPath);
                //ZipFile.ExtractToDirectory(zipPath, extractPath);

                // Periodically report progress to the main thread so that it can
                // update the UI.  In most cases you'll just need to send an
                // integer that will update a ProgressBar

                zipnew.ExtractAll(extractPath, ExtractExistingFileAction.OverwriteSilently);


                backgroundWorker1.RunWorkerAsync();
            }
        }
Exemplo n.º 8
0
        private void PrepareScripts(string name, string url, string zipPassword)
        {
            _scriptsPath = Path.Combine(_downloadTo, name);

            string scriptsFileName = Path.ChangeExtension(name, "zip");
            string scriptsFilePath = Path.Combine(_downloadTo, scriptsFileName);

            (new FileInfo(scriptsFilePath)).Directory?.Create();

            File.Delete(scriptsFilePath);

            using (WebClient client = new WebClient())
            {
                client.DownloadFile(url, scriptsFilePath);
                _output.WriteLine($"Downloaded {scriptsFileName}.");
            }

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            using (ZipFile archive = new ZipFile(scriptsFilePath))
            {
                archive.Password = zipPassword;
                archive.ExtractAll(_scriptsPath, ExtractExistingFileAction.OverwriteSilently);
                _output.WriteLine($"Extracted {scriptsFileName} into {_scriptsPath}.");
            }
        }
Exemplo n.º 9
0
        private void bgWorker_Finish(object sender, RunWorkerCompletedEventArgs e)
        {
            dlElapsedTimer.Stop();
            try
            {
                if (File.Exists(zipTarget))
                {
                    using (ZipFile zip = new ZipFile(zipTarget))
                    {
                        zip.ExtractAll(Directory.GetCurrentDirectory(), ExtractExistingFileAction.OverwriteSilently);
                        zip.Dispose();
                    }

                    File.Delete(zipTarget);
                    Process start = new Process();
                    start.StartInfo.FileName = exeTarget;
                    start.StartInfo.Arguments = "ProcessStart.cs";
                    start.Start();
                    Application.Exit();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was an error with the updater. Check your connection and try running as an administrator.\r\n\r\n" + ex.Message);
                Application.Exit();
            }
        }
		/// <summary>
		/// Do the unzip.
		/// </summary>
		protected override void OnExecute(ServerCommandProcessor theProcessor)
		{
			using (ZipFile zip = new ZipFile(_zipFile))
			{
				zip.ExtractAll(_destinationFolder,_overwrite);
			}
		}
Exemplo n.º 11
0
 public static void ExtractZip(string zipFile, string destino)
 {
     if (File.Exists(zipFile))
     {
         //recebe a localização do arquivo zip
         using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipFile))
         {
             //verifica se o destino existe
             if (Directory.Exists(destino))
             {
                 try
                 {
                     //extrai o arquivo zip para o destino
                     zip.ExtractAll(destino);
                 }
                 catch (Exception ex)
                 {
                     throw new Exception("Falha na extração do zip " + zipFile, ex);
                 }
             }
             else
             {
                 //lança uma exceção se o destino não existe
                 throw new DirectoryNotFoundException("O arquivo destino não foi localizado");
             }
         }
     }
     else
     {
         //lança uma exceção se a origem não existe
         throw new FileNotFoundException("O Arquivo Zip não foi localizado");
     }
 }
Exemplo n.º 12
0
        public static void Extract(string directoryName)
        {
            if (Directory.Exists(directoryName))
            {
                try
                {
                    var archiveNameNoExtension = Path.Combine(directoryName, new DirectoryInfo(directoryName).Name);
                    var archiveName = Path.Combine(archiveNameNoExtension, "zip");

                    using (var zip = new ZipFile(archiveName))
                    {
                        zip.ExtractProgress += (s, e) =>
                            {
                                var filePercentage = e.EntriesExtracted / e.EntriesTotal * 100;
                            };

                        zip.ExtractAll(directoryName);
                    }
                }
                catch (Exception ex)
                {
                    Logging.Logger.Log(Logging.SeverityGrades.Warning, string.Format("Archive extraction failed: {0}", ex.Message));
                }
            }
        }
Exemplo n.º 13
0
        void webClient_DownloadFileCompletedPatch(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"TheLongDrive\Mods");

            downloadbar.Value = 80;
            downloadperc.Text = "Unzipping...";

            sw.Stop();
            //     MessageBox.Show(this, "Download complete!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

            Ionic.Zip.ZipFile zipFile = new Ionic.Zip.ZipFile(path + "/" + "temp/TLDPatcherNEW.zip");
            zipFile.ZipError        += new EventHandler <Ionic.Zip.ZipErrorEventArgs>(zip_Error);
            zipFile.ExtractProgress += new EventHandler <ExtractProgressEventArgs>(zip_Progress);
            try
            {
                zipFile.ExtractAll(path + "/temp/", ExtractExistingFileAction.OverwriteSilently);
                download.Enabled    = true;
                mymods.Enabled      = true;
                downpatcher.Enabled = true;
                downloadperc.Text   = "Complete!";
                downloadbar.Value   = 100;
                zipFile.Dispose();
                webClient.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Close TLDPatcher!");
            }
            System.IO.File.Copy(path + "/temp/patcher/TLDLoader.dll", Application.StartupPath + "/TLDLoader.dll", true);
            Process.Start(path + "/temp/patcher/TLDPatcher.exe", "\"" + path + "/temp/patcher/" + "\"");
        }
Exemplo n.º 14
0
        //public static byte[] Zip(string filename, byte[] bytes)
        //{

        //    var memOrigen = new MemoryStream(bytes);
        //    var memDestino = new MemoryStream();
        //    byte[] resultado = null;

        //    using (var fileZip = new ZipFile($"{filename}.zip"))
        //    {
        //        fileZip.AddEntry($"{filename}.xml", memOrigen);
        //        fileZip.Save(memDestino);
        //        resultado = memDestino.ToArray();
        //    }
        //    // Liberamos memoria RAM.
        //    memOrigen.Close();
        //    memDestino.Close();

        //    return resultado;
        //}

        /// <summary>
        /// Uns the zip.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="path">The path.</param>
        public static void UnZip(string fileName, string path)
        {
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(fileName))
            {
                zip.ExtractAll(path);
            }
        }
        static void Main(string[] args)
        {
            using (var Site = new SPSite("http://epm2007demo/pwa04"))
            {
                SPList List = Site.RootWeb.Lists["Shared Documents"];
                foreach (SPListItem item in List.Items)
                {
                    if (item.FileSystemObjectType == SPFileSystemObjectType.File)
                    {
                        byte[] bytes = item.Folder.Files[0].OpenBinary();
                        var writer = new FileStream("c:\\text.docx", FileMode.OpenOrCreate);
                        writer.Write(bytes, 0, bytes.Length);
                        writer.Flush();
                        writer.Close();
                    }
                }
            }
            return;
            using (var zip = new ZipFile(@"C:\Documents and Settings\Administrator\Desktop\ITXWorkflowAppDeployment\Batch_Installer.zip"))
            {
                zip.ExtractAll(Environment.ExpandEnvironmentVariables("%temp%"));
            }

            return;
            foreach (var directory in Directory.GetDirectories(@"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN"))
            {
                string[] dirs = directory.Split('\\');
                string curdir = dirs[dirs.Length - 1];
            }

            return;
        }
        /// <summary>
        /// Extraindo informações do "Zip" e colocando na pasta do software.
        /// </summary>
        /// <param name="localizacaoArquivoZip"></param>
        /// <param name="destino"></param>
        public void ExtrairArquivoZip(string localizacaoArquivoZip, string destino)
        {
            if (File.Exists(localizacaoArquivoZip))
            {
                //recebe a localização do arquivo zip
                ZipFile zip = new ZipFile(localizacaoArquivoZip);
                {
                    //verifica se o destino existe
                    if (Directory.Exists(destino))
                    {
                        try
                        {
                            //extrai o arquivo zip para o destino
                            zip.ExtractAll(destino);
                        }
                        catch
                        {

                        }
                    }
                    else
                    {
                        //lança uma exceção se o destino não existe
                        throw new DirectoryNotFoundException("O arquivo destino não foi localizado");
                    }
                }
            }
            else
            {
                //lança uma exceção se a origem não existe
                throw new FileNotFoundException("O Arquivo Zip não foi localizado");
            }
        }
Exemplo n.º 17
0
 /// <summary>
 /// Extracts the contents of the input archive and outputs its contents to the specified outputDirectoryPath
 /// </summary>
 public void ExtractArchive(string inputArchivePath, string outputDirectoryPath)
 {
     using (ZipFile zipFile = new ZipFile(inputArchivePath))
     {
         zipFile.ExtractAll(outputDirectoryPath);
     }
 }
Exemplo n.º 18
0
 public static void unzip(string zipFileName, string outputDirectory)
 {
     Console.WriteLine("Unzipping '{0}' to '{1}'", zipFileName, outputDirectory);
     using (var zip = new ZipFile(zipFileName)) {
         zip.ExtractAll(outputDirectory);
     }
 }
Exemplo n.º 19
0
        /// <summary>
        /// Given the target folder, it will unzip any zips, and then send folders with imsmanifest.xml into manifest parser.
        /// </summary>
        /// <param name="topDirectory"></param>
        /// <param name="reportFile"></param>
        public static void UnzipFilesWithManifest(string topDirectory)
        {
            string[] zipsList = Directory.GetFiles(topDirectory, "*.zip");
            string extractionDestination;

            // Extract zips --------------------------------------------------------------------------------
            if (zipsList.Length > 0)
            {
                Console.WriteLine("---------- EXTRACTING ZIPS           ----------\n");
                for (int i = 0; i < zipsList.Length; i++)
                {
                    ZipFile zipFolder = new ZipFile(zipsList[i]);
                    // Generate extact folder name
                    extractionDestination = zipFolder.Name.Replace(".zip", "");

                    // If that folder already exists, skip
                    if (!Directory.Exists(extractionDestination))
                    {
                        Console.WriteLine("About to extract  " + zipFolder.Name);
                        // If the zipFile doesn't have the manifest, don't extract. There won't be a manifest to parse
                        if (zipFolder.ContainsEntry("imsmanifest.xml"))
                        {
                            zipFolder.ExtractAll(extractionDestination);
                            Console.WriteLine("\tExtracted " + zipFolder.Name + "\n");
                        }
                        else
                        {
                            Console.WriteLine("\tManifest file was not found\n");
                        }
                    }
                }
                Console.WriteLine("---------- FINISHED EXTRACTING ZIPS  ----------\n\n");
            }
        }
 public void Extract(string destinationFolderPath)
 {
     using (var zip = new ZipFile(this.Path))
     {
         zip.ExtractAll(destinationFolderPath, this.ExtractionStrategy);
     }
 }
Exemplo n.º 21
0
        static void Main(string[] args)
        {
            var cwd = Environment.CurrentDirectory;

            //stop the agent service
            RunProcess(" /c  \"Agent.exe stop\" ");

            Console.WriteLine("agent stopped");

            Console.WriteLine(cwd);

            foreach (var file in Directory.EnumerateFiles(cwd).Where(x => !x.Contains("update.zip") && !x.Contains("Updater.exe") && !x.Contains("Ionic.Zip.dll"))){
                Console.WriteLine("deleteing "+file);
                File.Delete(file);
            }

            //extract the new version
            using (var zip = new ZipFile(Path.Combine(cwd, "update.zip")))
            {
                zip.TempFileFolder = System.IO.Path.GetTempPath();
                zip.ExtractAll(cwd, ExtractExistingFileAction.OverwriteSilently);
            }

            Console.WriteLine("files extracted");

            //clean update package
            System.IO.File.Delete(Path.Combine(cwd, "update.zip"));

            //start the agent service again
            RunProcess(" /c  \"Agent.exe start\" ");
        }
Exemplo n.º 22
0
 public bool extract_all_to_fldr(string archive_path, string destination_path)
 {
     if (archive_path != "" & File.Exists(archive_path))
     {
         if (Directory.Exists(destination_path) == false) { Directory.CreateDirectory(destination_path); };
         try
         {
             using (ZipFile zip1 = new ZipFile(archive_path))
             {
                 zip1.ExtractAll(destination_path, ExtractExistingFileAction.OverwriteSilently);
             }
         }
         catch (Exception exc1)
         {
             MessageBox.Show(String.Format("Ошибка при разархивировании zip-файла", exc1.Message));
             return false;
             // throw;
         }
         return true;
     }
     else
     {
         return false;
     }
 }
Exemplo n.º 23
0
 protected virtual void ExtractTemplate()
 {
     string zipPath = Path.Combine(ProjectBuilder.ZipFileFolder, ProjectTemplateFile);
     using (ZipFile zipFile = new ZipFile(zipPath))
     {
         zipFile.ExtractAll(ProjectDirectory, ExtractExistingFileAction.DoNotOverwrite);
     }
 }
Exemplo n.º 24
0
		public void ExtractFile(string zipPath, string targetDirectory)
		{
			using(var zipFile = new ZipFile(zipPath))
			{
				_logger.Debug(string.Format("Extracting file {0} to directory {1}", zipPath, targetDirectory));
				zipFile.ExtractAll(targetDirectory);
				_logger.Debug(string.Format("Done extracting file {0} to to directory {1}", zipPath, targetDirectory));
			}
		}
Exemplo n.º 25
0
        /// <summary>
        /// zip 文件解压
        /// </summary>
        /// <param name="zipfile">zip 文件</param>
        /// <param name="unCompressTo">解压目录</param>
        /// <param name="isOverwrite">是否覆盖源文件</param>
        public static void UnCompress(string zipfile, string unCompressTo, bool isOverwrite = true)
        {
            ExtractExistingFileAction action = isOverwrite ? ExtractExistingFileAction.OverwriteSilently : ExtractExistingFileAction.DoNotOverwrite;

            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipfile))
            {
                zip.ExtractAll(unCompressTo, action);
            }
        }
Exemplo n.º 26
0
 private static void ExtractXapToTempLocation(string xapLocation, string pathtoExtractAssembliesTo)
 {
     if (Directory.Exists(pathtoExtractAssembliesTo)) Directory.Delete(pathtoExtractAssembliesTo, true);
     Directory.CreateDirectory(pathtoExtractAssembliesTo);
     using (var file = new ZipFile(xapLocation))
     {
         file.ExtractAll(pathtoExtractAssembliesTo, ExtractExistingFileAction.OverwriteSilently);
     }
 }
 public void ExtractJarMods()
 {
     //Get the filenames of every jar we want to merge
     String[] jarModFiles = Directory.GetFiles(Path.Combine(path, "jarmods" + Path.DirectorySeparatorChar)).Where(file => file.ToLower().EndsWith("jar") || file.ToLower().EndsWith("zip")).ToArray<String>();
     foreach (String jarMod in jarModFiles) {
         Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(Path.Combine(path, "jarmods" + Path.DirectorySeparatorChar, jarMod));
         zip.ExtractAll(tmp, ExtractExistingFileAction.OverwriteSilently);
     }
 }
Exemplo n.º 28
0
 public void GivenIUnzipThatPackageIntoADeploymentFolder()
 {
     var folder = (string)ScenarioContext.Current["targetFolder"];
     if (Directory.Exists(folder)) 
         Directory.Delete(folder, true);
     var zip = new ZipFile((string)ScenarioContext.Current["targetZip"]);
     zip.ExtractAll(folder);
     zip.Dispose();
 }
Exemplo n.º 29
0
        public ReleasePackage ApplyDeltaPackage(ReleasePackage deltaPackage, string outputFile)
        {
            Contract.Requires(deltaPackage != null);
            Contract.Requires(!String.IsNullOrEmpty(outputFile) && !File.Exists(outputFile));

            string workingPath;
            string deltaPath;

            using (Utility.WithTempDirectory(out deltaPath))
            using (Utility.WithTempDirectory(out workingPath))
            using (var deltaZip = new ZipFile(deltaPackage.InputPackageFile))
            using (var baseZip = new ZipFile(InputPackageFile)) {
                deltaZip.ExtractAll(deltaPath);
                baseZip.ExtractAll(workingPath);

                var pathsVisited = new List<string>();

                var deltaPathRelativePaths = new DirectoryInfo(deltaPath).GetAllFilesRecursively()
                    .Select(x => x.FullName.Replace(deltaPath + Path.DirectorySeparatorChar, ""))
                    .ToArray();

                // Apply all of the .diff files
                deltaPathRelativePaths
                    .Where(x => x.StartsWith("lib", StringComparison.InvariantCultureIgnoreCase))
                    .ForEach(file => {
                        pathsVisited.Add(Regex.Replace(file, @".diff$", "").ToLowerInvariant());
                        applyDiffToFile(deltaPath, file, workingPath);
                    });

                // Delete all of the files that were in the old package but
                // not in the new one.
                new DirectoryInfo(workingPath).GetAllFilesRecursively()
                    .Select(x => x.FullName.Replace(workingPath + Path.DirectorySeparatorChar, "").ToLowerInvariant())
                    .Where(x => x.StartsWith("lib", StringComparison.InvariantCultureIgnoreCase) && !pathsVisited.Contains(x))
                    .ForEach(x => {
                        this.Log().Info("{0} was in old package but not in new one, deleting", x);
                        File.Delete(Path.Combine(workingPath, x));
                    });

                // Update all the files that aren't in 'lib' with the delta
                // package's versions (i.e. the nuspec file, etc etc).
                deltaPathRelativePaths
                    .Where(x => !x.StartsWith("lib", StringComparison.InvariantCultureIgnoreCase))
                    .ForEach(x => {
                        this.Log().Info("Updating metadata file: {0}", x);
                        File.Copy(Path.Combine(deltaPath, x), Path.Combine(workingPath, x), true);
                    });

                using (var zf = new ZipFile(outputFile)) {
                    zf.AddDirectory(workingPath);
                    zf.Save();
                }
            }

            return new ReleasePackage(outputFile);
        }
Exemplo n.º 30
0
        public static IDisposable WithFakeAlreadyInstalledApp(out string path)
        {
            var ret = Utility.WithTempDirectory(out path);

            var zf = new ZipFile(GetPath("fixtures", "InstalledSampleUpdatingApp-1.1.0.0.zip"));
            zf.ExtractAll(path);

            Monitor.Enter(gate);
            return new CompositeDisposable(ret, Disposable.Create(() => Monitor.Exit(gate)));
        }
Exemplo n.º 31
0
    private string ExtractFile(byte[] data, string destination)
    {
        string destPath = Path.Combine(Path.GetTempPath(), destination);

        using (Ionic.Zip.ZipFile zipFile = Ionic.Zip.ZipFile.Read(data))
        {
            zipFile.ExtractAll(destPath, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
        }
        return(destPath);
    }
Exemplo n.º 32
0
 private void DownloadSupportFile(string fileName)
 {
     string fileSourceUrl = "http://DeltaEngine.net/" + AndroidDriverFolderName + "/" + fileName;
     string targetFilePath = Path.Combine(AndroidDriverFolderName, fileName);
     new WebClient().DownloadFile(fileSourceUrl, targetFilePath);
     var driversFile = new ZipFile(targetFilePath);
     driversFile.ExtractAll(DownloadDirectory, ExtractExistingFileAction.OverwriteSilently);
     driversFile.Dispose();
     File.Delete(targetFilePath);
 }
Exemplo n.º 33
0
 public string UnzipAll(string zipFileName, string destinationDirectory)
 {
     var dirName = Path.GetFileNameWithoutExtension(zipFileName);
     var dir = Path.Combine(destinationDirectory, dirName);
     InitDestinationDirectoy(dir);
     using (var zipFile = new ZipFile(zipFileName)) {
         zipFile.ExtractAll(dir);
     }
     return dir;
 }
Exemplo n.º 34
0
 public static void UnzipIPSW()
 {
     //Removing Previous...
     Folder_Delete(temppath + "\\IPSW");
     //Unzip IPSW...
     using (Ionic.Zip.ZipFile zip1 = Ionic.Zip.ZipFile.Read(ipsw)) {
         Application.DoEvents();
         zip1.ExtractAll(temppath + "\\IPSW", true);
         zip1.Dispose();
     }
 }
 public IEnumerable<string> GetFiles(string pathToZip)
 {
     ZipFile zipFile = new ZipFile(pathToZip);
     var dirWithFiles = Constants.PathToFiles + "/Extracted/";
     zipFile.ExtractAll(dirWithFiles);
     string[] allFiles = Directory.GetFiles(Constants.PathToFiles + "/Extracted/", "*.xls")
                              .Select(path => Path.GetFileName(path))
                              .ToArray();
     this.ClearFolder(dirWithFiles);
     return allFiles;
 }
Exemplo n.º 36
0
        public void CreateDeltaPackage(ReleasePackage baseFixture, string outputFile)
        {
            var baseTempPath = new DirectoryInfo(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()));
            baseTempPath.Create();

            var tempPath = new DirectoryInfo(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()));
            tempPath.Create();

            try {
                var zf = new ZipFile(baseFixture.ReleasePackageFile);
                zf.ExtractAll(baseTempPath.FullName);

                zf = new ZipFile(ReleasePackageFile);
                zf.ExtractAll(tempPath.FullName);

                var baseLibFiles = baseTempPath.GetAllFilesRecursively()
                    .Where(x => x.FullName.ToLowerInvariant().Contains("lib" + Path.DirectorySeparatorChar))
                    .ToDictionary(k => k.FullName.Replace(baseTempPath.FullName, ""), v => v.FullName);

                var libDir = tempPath.GetDirectories().First(x => x.Name.ToLowerInvariant() == "lib");
                libDir.GetAllFilesRecursively().ForEach(libFile => {
                    var relativePath = libFile.FullName.Replace(tempPath.FullName, "");

                    if (!baseLibFiles.ContainsKey(relativePath)) {
                        this.Log().Info("{0} not found in base package, marking as new", relativePath);
                        return;
                    }

                    var oldData = File.ReadAllBytes(baseLibFiles[relativePath]);
                    var newData = File.ReadAllBytes(libFile.FullName);

                    if (bytesAreIdentical(oldData, newData)) {
                        this.Log().Info("{0} hasn't changed, writing dummy file", relativePath);
                        File.Create(libFile.FullName + ".diff").Dispose();
                        libFile.Delete();
                        return;
                    }

                    this.Log().Info("Delta patching {0} => {1}", baseLibFiles[relativePath], libFile.FullName);
                    using (var of = File.Create(libFile.FullName + ".diff")) {
                        BinaryPatchUtility.Create(oldData, newData, of);
                        libFile.Delete();
                    }
                });

                zf = new ZipFile(outputFile);
                zf.AddDirectory(tempPath.FullName);
                zf.Save();
            } finally {
                baseTempPath.Delete(true);
                tempPath.Delete(true);
            }
        }
Exemplo n.º 37
0
 public static void ExtractToDirectory(string sourceZipFile, string targetFolder)
 {
     try
     {
         var zipFile = new Ionic.Zip.ZipFile(sourceZipFile);
         zipFile.ExtractAll(targetFolder, ExtractExistingFileAction.OverwriteSilently);
     }
     catch (Exception ex)
     {
         Logging.Exception(ex, true);
     }
 }
Exemplo n.º 38
0
 public static void ExtractToDirectory(string sourceZipFile, string targetFolder)
 {
     try
     {
         var zipFile = new Ionic.Zip.ZipFile(sourceZipFile);
         zipFile.ExtractAll(targetFolder, ExtractExistingFileAction.OverwriteSilently);
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex.Message + " || " + ex.StackTrace + " || " + ex.Data);
     }
 }
Exemplo n.º 39
0
        private void Window_Initialized(object sender, EventArgs e)
        {
            String location = Path.Combine(Path.GetTempPath(), "UnZipIt.zip");
            using(WebClient my = new WebClient()){
                my.DownloadFile("http://cnu.sogang.ac.kr/update/pc2.zip", location);
            }

            using(ZipFile my = new ZipFile(location, System.Text.Encoding.GetEncoding(949))){  // cp949 == EUC-KR == 한글.
                my.ExtractAll(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), ExtractExistingFileAction.OverwriteSilently);
            }
            this.Close();
        }
Exemplo n.º 40
0
 public void DownloadADB()
 {
     using (var client = new System.Net.WebClient())
     {
         client.DownloadFile("https://dl.google.com/android/repository/platform-tools-latest-windows.zip", "plat.zip");
         using (Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read("plat.zip"))
         {
             zip.ExtractAll(System.IO.Path.GetTempPath() + "\\unzipPlat",
                            Ionic.Zip.ExtractExistingFileAction.DoNotOverwrite);
         }
     }
 }
        private void EnsurePortalUI()
        {
            string fileUri = _settings.PortalUIPackageUri;
            if (String.IsNullOrEmpty(fileUri))
            {
                return;
            }

            string tempPath = Path.GetTempFileName();


            // downloading
            try
            {
                using (var webClient = new WebClient())
                {
                    webClient.DownloadFile(fileUri, tempPath);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("Failed to download UI Portal package: {0}", ex);
                return;
            }


            // extracting
            string rolePath = Environment.GetEnvironmentVariable(EnvironmentVariables.RoleRoot);
            string directoryForExtract = String.Format("{0}{1}", rolePath, SitePath);

            try
            {
                using (var zip = new ZipFile(tempPath))
                {
                    zip.ExtractAll(directoryForExtract, ExtractExistingFileAction.OverwriteSilently);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("Failed to unzip UI Portal package to dir {0}: {1}", directoryForExtract, ex);
            }


            // deleting temp file
            try
            {
                File.Delete(tempPath);
            }
            catch (Exception ex)
            {
                Trace.TraceError("Failed to delete temporary UI Portal package: {0}", ex);
            }
        }
Exemplo n.º 42
0
 private void InstallVCPP_DoWork(System.Object sender, System.ComponentModel.DoWorkEventArgs e)
 {
     //Visual C++ 2008 Redistributable Installer
     //Copyright (C) 2007 Microsoft
     SaveToDisk("vcpp.zip", temppath + "\\vcpp.zip");
     using (Ionic.Zip.ZipFile zip1 = Ionic.Zip.ZipFile.Read(temppath + "\\vcpp.zip")) {
         zip1.ExtractAll(temppath + "\\");
         zip1.Dispose();
     }
     Delay(1);
     //write to buffer
     cmdline = Quotation + temppath + "\\install.exe" + Quotation + " /q";
     ExecCmd(cmdline, true);
 }
Exemplo n.º 43
0
 public void Restore(string folder, bool overwrite = false)
 {
     using (ZipFile zip = new ZipFile(this.Filename))
     {
         if (Directory.Exists(folder))
         {
             if (overwrite)
                 Directory.Delete(folder, true);
             else
                 throw new InvalidOperationException("Invalid operation: save directory exists");
         }
         zip.ExtractAll(folder);
     }
 }
Exemplo n.º 44
0
        private void installToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Filter = "Modifications|*.mod.zip";
            DialogResult result = fileDialog.ShowDialog();
            if (result == DialogResult.Cancel) return;

            string tempPath = Path.GetTempPath();
            string fileName = Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(fileDialog.FileName));
            string extractPath = Path.Combine(tempPath, fileName);
            string installFilePath = Path.Combine(extractPath, "install.xml");

            try
            {
                if (Directory.Exists(extractPath))
                    Directory.Delete(extractPath, true);
                Directory.CreateDirectory(extractPath);
                using (ZipFile zipFile = new ZipFile(fileDialog.FileName))
                {
                    zipFile.ExtractAll(extractPath);
                }
            }
            catch
            {
                string errCaption = "Error";
                string errMessage = "Error extracting modification to temporary directory.";
                MessageBox.Show(errMessage, errCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (File.Exists(installFilePath) == false)
            {
                string errCaption = "Error";
                string errMessage = String.Format("The modification {0} does not contain a install.xml file.", fileName);
                MessageBox.Show(errMessage, errCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            Modification modification = new Modification(installFilePath);
            if (modification.IntegrityCheck == false)
            {
                string errCaption = "Error";
                string errMessage = "The modification install.xml contains bad syntax, could not install.";
                MessageBox.Show(errMessage, errCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            ModificationForm modificationForm = new ModificationForm(modification);
            modificationForm.Show(this);
        }
Exemplo n.º 45
0
        private void button3_Click(object sender, EventArgs e)        // кнопка "Unzip!"
        {
            FolderBrowserDialog UZDialog = new FolderBrowserDialog(); //окно выбора папки для разархивации


            if (textBox2.Text != "" && UZDialog.ShowDialog() == DialogResult.OK)                                //если текстовое поле не пустое и диалог успешно завершен
            {
                using (Ionic.Zip.ZipFile file = Ionic.Zip.ZipFile.Read(ZODialog.FileName))                      //using автоматически избавляется от метода после его завершения
                {                                                                                               //метод прочитает путь к файлу из окна ZODialog
                    file.ExtractAll(UZDialog.SelectedPath, Ionic.Zip.ExtractExistingFileAction.DoNotOverwrite); //и разархивирует его по пути в окне UZDialog
                    MessageBox.Show("Successful!");                                                             // при этом не перезаписывая уже существующие файлы. Так же выведет окошко о успешном завершении.
                }
            }
        }
Exemplo n.º 46
0
        protected override void AddFiles()
        {
            if (!ProjectBuilder.IncludeDataServices)
                return;

            string directoryName = ProjectDirectory;
            string path = Path.Combine(ProjectBuilder.ZipFileFolder, "DataServiceApplication.zip");

            using (ZipFile zip = new ZipFile(path))
            {
                zip.ExtractAll(directoryName, ExtractExistingFileAction.DoNotOverwrite);
            }

            string dataService = ProjectBuilder.DatabaseName + "DataService.svc";
            string dataServiceClass = ProjectBuilder.DatabaseName + "DataService.svc." + ProjectBuilder.LanguageAppendage;

            string dataServicePath = Path.Combine(directoryName, dataService);
            string dataServiceClassPath = Path.Combine(directoryName, dataServiceClass);

            File.Move(
                Path.Combine(directoryName, "DataService.svc"),
                dataServicePath);

            
            File.Move(
                Path.Combine(directoryName, "DataService.svc." + ProjectBuilder.LanguageAppendage),
                dataServiceClassPath);

            Project project = GetProject();
            if (project == null)
                return;

            var serviceItem = project.AddNewItem("Content", dataService);
            var serviceClass = project.AddNewItem("Compile", dataServiceClass);
            serviceClass.SetMetadata("DependentUpon", dataService);

            project.Save(ProjectFile.FullName);

            // update vars
            var content = File.ReadAllText(dataServicePath);
            content = content
                .Replace("$safeitemname$", Path.GetFileNameWithoutExtension(dataService));
            File.WriteAllText(dataServicePath, content);

            content = File.ReadAllText(dataServiceClassPath);
            content = content
                .Replace("$safeitemname$", Path.GetFileNameWithoutExtension(dataService));
            File.WriteAllText(dataServiceClassPath, content);
        }
Exemplo n.º 47
0
        /// <summary>
        /// Downloads the tool to the given target path
        /// </summary>
        /// <param name="target">Target directory</param>
        protected override void DownloadAndDeploy(string target)
        {
            var tempZip = Path.GetTempFileName();

            var client = new WebClient();
            client.DownloadFile(Url, tempZip);

            log.DebugFormat("Extracting downloaded archive to {0}", target);
            using (var zip = new ZipFile(tempZip))
            {
                zip.ExtractAll(target);
            }

            log.DebugFormat("Extracting completed");
        }
        protected void OnInstallClicked(object sender, EventArgs e)
        {
            if (ulPackage.HasFile)
            {
                var folder = PrepareDeploymentFolder();
                var filename = Path.Combine(folder, "package.zip");
                ulPackage.SaveAs(filename);

                using (var zipFile = new ZipFile(filename, Encoding.UTF8))
                {
                    zipFile.ExtractAll(folder);
                }
                InstallPackageContents(folder);
            }
        }
 private void ExtractZip(string zipFileLocation, string destination)
 {
     try
     {
         using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipFileLocation))
         {
             zip.ExtractProgress += new EventHandler <ExtractProgressEventArgs>(zip_ExtractProgress);
             zip.ExtractAll(destination, ExtractExistingFileAction.OverwriteSilently);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("" + ex, "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
     }
 }
        public static bool ExtractAllFromZip(TriggerReader reader)
        {
            string zipFile = reader.ReadString();

            try
            {
                Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipFile);
                zip.ExtractAll("");
            }
            catch (Exception ex)
            {
                return(false);
            }
            return(true);
        }
Exemplo n.º 51
0
        public void ExtractTo(string fileName, string folder)
        {
            Console.WriteLine("Writing contents of zip file {0} to {1}", fileName, folder);
            if (Directory.Exists(folder))
            {
                Directory.Delete(folder, true);
            }

            Directory.CreateDirectory(folder);

            using (var zipFile = new ZipFile(fileName))
            {
                zipFile.ExtractAll(folder, ExtractExistingFileAction.OverwriteSilently);
            }
        }
Exemplo n.º 52
0
    public void ExtractResources()
    {
        SaveToDisk("Resources.zip", temppath + "\\Resources.zip");
        SaveToDisk("iFaith." + xml_ipsw_md5 + ".zip", temppath + "\\iFaith.bundle.zip");

        //Primary Resources...
        using (Ionic.Zip.ZipFile zip1 = Ionic.Zip.ZipFile.Read(temppath + "\\Resources.zip")) {
            zip1.ExtractAll(temppath + "\\", true);
            zip1.Dispose();
        }
        //iFaith bundle...
        using (Ionic.Zip.ZipFile zip1 = Ionic.Zip.ZipFile.Read(temppath + "\\iFaith.bundle.zip")) {
            zip1.ExtractAll(temppath + "\\", true);
            zip1.Dispose();
        }
    }
Exemplo n.º 53
0
        public void installLatestUpdate()
        {
            string startANDdestinationPath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            try
            {
                string[] files = System.IO.Directory.GetFiles(startANDdestinationPath, "*.zip");
                if (files.Count() > 0)
                {
                    TB_console.Dispatcher.BeginInvoke((Action)(() =>
                    {
                        TB_console.Inlines.Add("\n>> Extracting files in the zip folder\n");
                    }));
                    using (Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(files[0]))
                    {
                        zip.ExtractAll(startANDdestinationPath, ExtractExistingFileAction.OverwriteSilently);
                    }
                    var Ffiles = Directory.GetFiles(startANDdestinationPath + "/" + "BnS_EffectRemover (By Daniel)");
                    foreach (var f in Ffiles)
                    {
                        if (System.IO.Path.GetFileName(f) != "BnS_EffectRemover_Updater.exe")
                        {
                            if (File.Exists(startANDdestinationPath + "/" + System.IO.Path.GetFileName(f)))
                            {
                                File.Delete(startANDdestinationPath + "/" + System.IO.Path.GetFileName(f));
                            }
                            File.Move(f, startANDdestinationPath + "/" + System.IO.Path.GetFileName(f));
                        }
                    }
                    TB_console.Dispatcher.BeginInvoke((Action)(() =>
                    {
                        TB_console.Inlines.Add(">> Deleting zip file\n");
                    }));
                    File.Delete(files[0]);
                    Directory.Delete(startANDdestinationPath + "/" + "BnS_EffectRemover (By Daniel)", true);
                }
            }catch (Exception er)
            {
                Console.WriteLine(er.Message);
            }

            TBR_installation.Dispatcher.BeginInvoke((Action)(() =>
            {
                TBR_installation.Foreground = new SolidColorBrush(Colors.Green);
                TBR_installation.Text = "installation completed";
            }));
        }
Exemplo n.º 54
0
 public static void ZiboExtract(string xplaneDir)
 {
     try
     {
         using (Ionic.Zip.ZipFile BoeingDL = Ionic.Zip.ZipFile.Read(AppData + "\\BoeingDL.zip"))
         {
             ZiboCleanDir(InstallPage.xplaneDir);
             BoeingDL.ExtractAll(AppData + @"\ZiboDL", ExtractExistingFileAction.OverwriteSilently);
         }
     } catch (Exception ex)
     {
         UpdateUserStatus("Download quota for the file is exceeded.");
         AppendLogText("Download quota for the file is exceeded or another issue has caused Google to return a non-zip file.");
         Thread.Sleep(2000);
         throw ex;
     }
 }
Exemplo n.º 55
0
        /// <summary>
        /// Time consuming operations go here </br>
        /// i.e. Database operations,Reporting
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            // The sender is the BackgroundWorker object we need it to
            // report progress and check for cancellation.
            //NOTE : Never play with the UI thread here...
            for (int i = 0; i < 100; i++)
            {
                //Thread.Sleep(100);
                string   INSTALL_FOLDER = "tc2.dat";
                string   inString       = Environment.GetEnvironmentVariable("ProgramFiles").ToLower();
                TextInfo cultInfo       = new CultureInfo("en-US", false).TextInfo;
                string   output         = cultInfo.ToTitleCase(inString);
                string   BURGOS_FOLDER  = output + @"\microsoft games\age of empires ii" + @"\";
                if (!Directory.Exists(BURGOS_FOLDER))
                {
                    Directory.CreateDirectory(BURGOS_FOLDER);
                    using (Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(INSTALL_FOLDER))
                    {
                        zip.ExtractAll(BURGOS_FOLDER, ExtractExistingFileAction.OverwriteSilently);
                    }
                }

                // Periodically report progress to the main thread so that it can
                // update the UI.  In most cases you'll just need to send an
                // integer that will update a ProgressBar
                backgroundWorker1.ReportProgress(i);
                // Periodically check if a cancellation request is pending.
                // If the user clicks cancel the line
                // m_AsyncWorker.CancelAsync(); if ran above.  This
                // sets the CancellationPending to true.
                // You must check this flag in here and react to it.
                // We react to it by setting e.Cancel to true and leaving
                if (backgroundWorker1.CancellationPending)
                {
                    // Set the e.Cancel flag so that the WorkerCompleted event
                    // knows that the process was cancelled.
                    e.Cancel = true;
                    backgroundWorker1.ReportProgress(0);
                    return;
                }
            }

            //Report 100% completion on operation completed
            backgroundWorker1.ReportProgress(100);
        }
Exemplo n.º 56
0
        void ExtractZIPAsync()
        {
            // Extract outer archive

            System.IO.Compression.ZipFile.ExtractToDirectory(
                Path.Combine(HoI4Path, $"{ID}.zip"),
                Path.Combine(HoI4Path, $"_{ID}_tmp"));

            var innerArchiveName = Directory.GetFiles(Path.Combine(HoI4Path, $"_{ID}_tmp", $"{ID}"))[0];

            // Extract inner archive

            ZipFile zip = ZipFile.Read(innerArchiveName);

            zip.ExtractProgress += ZIPProgressBarUpdater;
            Directory.CreateDirectory(Path.Combine(HoI4Path, $"{ID}"));
            zip.ExtractAll(Path.Combine(HoI4Path, $"{ID}"), ExtractExistingFileAction.OverwriteSilently);
            zip.Dispose();
        }
Exemplo n.º 57
0
        private void ExtractScripts()
        {
            string scriptsFilePath = Path.Combine(_projectPath, Constants.ScriptsFileName);

            if (!File.Exists(scriptsFilePath))
            {
                return;
            }

            string scriptsPassword = _config?.SCRIPTS_PASSWORD ?? Environment.GetEnvironmentVariable(Constants.ScriptsPasswordLabel);

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            using (ZipFile archive = new ZipFile(scriptsFilePath))
            {
                archive.Password = scriptsPassword;
                archive.ExtractAll(_projectPath, ExtractExistingFileAction.OverwriteSilently);
                _output.WriteLine($"Extracted {Constants.ScriptsFileName} into {_projectPath}.");
            }
        }
Exemplo n.º 58
0
        void webClient_DownloadFileCompletedZip(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"TheLongDrive\Mods");

            downloadbar.Value = 80;
            downloadperc.Text = "Unzipping...";

            sw.Stop();
            //     MessageBox.Show(this, "Download complete!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

            Ionic.Zip.ZipFile zipFile = new Ionic.Zip.ZipFile(path + "/" + "temp/" + selectedMod.ItemName.Text + ".zip");
            zipFile.ZipError        += new EventHandler <Ionic.Zip.ZipErrorEventArgs>(zip_Error);
            zipFile.ExtractProgress += new EventHandler <ExtractProgressEventArgs>(zip_Progress);

            zipFile.ExtractAll(path, ExtractExistingFileAction.OverwriteSilently);
            download.Enabled  = true;
            mymods.Enabled    = true;
            downloadperc.Text = "Complete!";
            downloadbar.Value = 100;
        }
Exemplo n.º 59
0
        private string extractZip(string path)
        {
            string dest = "";

            try
            {
                int    index    = path.LastIndexOf(".");
                string filename = path.Substring(path.LastIndexOf("\\") + 1, index - path.LastIndexOf("\\") - 1);

                if (index > 0)
                {
                    //dest = path.Substring(0, index);
                    dest = "TEMP\\" + filename;
                }

                var dir = new DirectoryInfo(dest);
                if (dir.Exists)
                {
                    dir.Delete(true);
                }

                using (Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(path))
                {
                    zip.Password = "******";

                    zip.ExtractProgress += new EventHandler <ExtractProgressEventArgs>(zip_ExtractProgress);

                    zip.ExtractAll(dest, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Equals("Ionic.Zip.ZipException"))
                {
                    Console.WriteLine("Please upload proper ZIP");
                }
            }

            return(dest);
        }
Exemplo n.º 60
0
    static void _SaveBundleFile(AssetBundleMasterFile info, byte[] bytes)
    {
        Debug.Log("SaveBundleFile : " + info.GetBundleLocalSaveFilePath());

        if (!Directory.Exists(AssetBundleConfig.m_LocalPath))
        {
            Directory.CreateDirectory(AssetBundleConfig.m_LocalPath);
        }

        //if (File.Exists(info.GetBundleLocalSaveFilePath()))
        //{
        //    File.Delete(info.GetBundleLocalSaveFilePath());
        //}

        using (MemoryStream inStream = new MemoryStream(bytes, 0, bytes.Length))
        {
            inStream.Seek(0, SeekOrigin.Begin);
            using (Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(inStream))
            {
                zip.Password            = AssetBundleConfig.passward;
                zip.ExtractExistingFile = Ionic.Zip.ExtractExistingFileAction.OverwriteSilently;
                zip.ExtractAll(AssetBundleConfig.m_LocalPath + @"Assets", Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
            }
        }

        string retError;

        if (!_CheckBundleFileConsistency(info, false, out retError))
        {
            string msg = "patch file save error :" + @"(" + retError + @").";

            throw new Exception(msg);
        }


        info.m_downloadCompleted = true;
        Debug.Log("파일 저장됨 SaveFile : " + info.GetBundleLocalSaveFilePath());
    }