Ejemplo n.º 1
0
        public override void OpenFile(OpenFileArgs args)
        {
            string tempFolder    = Path.Combine(Utils.GetTempFolder(), "dnGREP-Archive", Utils.GetHash(args.SearchResult.FileNameReal));
            string innerFileName = args.SearchResult.FileNameDisplayed.Substring(args.SearchResult.FileNameReal.Length).TrimStart(Path.DirectorySeparatorChar);
            string filePath      = Path.Combine(tempFolder, innerFileName);

            if (!File.Exists(filePath))
            {
                // use the directory name to also include folders within the archive
                string directory = Path.GetDirectoryName(filePath);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                using (SevenZipExtractor extractor = new SevenZipExtractor(args.SearchResult.FileNameReal))
                {
                    if (extractor.ArchiveFileData.Where(r => r.FileName == innerFileName && !r.IsDirectory).Any())
                    {
                        using (FileStream stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                        {
                            try
                            {
                                extractor.ExtractFile(innerFileName, stream);
                            }
                            catch
                            {
                                args.UseBaseEngine = true;
                            }
                        }
                    }
                }
            }

            if (Utils.IsPdfFile(filePath) || Utils.IsWordFile(filePath) || Utils.IsExcelFile(filePath))
            {
                args.UseCustomEditor = false;
            }

            GrepSearchResult newResult = new GrepSearchResult();

            newResult.FileNameReal      = args.SearchResult.FileNameReal;
            newResult.FileNameDisplayed = args.SearchResult.FileNameDisplayed;
            OpenFileArgs newArgs = new OpenFileArgs(newResult, args.Pattern, args.LineNumber, args.UseCustomEditor, args.CustomEditor, args.CustomEditorArgs);

            newArgs.SearchResult.FileNameDisplayed = filePath;
            Utils.OpenFile(newArgs);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 7z解压缩
        /// </summary>
        /// <param name="filePath">压缩文件路径</param>
        /// <param name="extractFolder">解压缩目录</param>
        /// <param name="password">解压缩密码</param>
        /// <param name="fileExtractionStarted">文件解压缩开始事件</param>
        /// <param name="fileExists">文件存在事件</param>
        /// <param name="extracting">解压进度事件</param>
        /// <param name="fileExtractionFinished">解压缩完成事件</param>
        /// <returns>解压结果</returns>
        public static bool ExtractFrom7z(
            string filePath,
            string extractFolder,
            string password = null,
            EventHandler <FileInfoEventArgs> fileExtractionStarted  = null,
            EventHandler <FileOverwriteEventArgs> fileExists        = null,
            EventHandler <ProgressEventArgs> extracting             = null,
            EventHandler <FileInfoEventArgs> fileExtractionFinished = null)
        {
            var result = true;

            try
            {
                SevenZipExtractor tmp = null;
                if (!string.IsNullOrEmpty(password))
                {
                    tmp = new SevenZipExtractor(filePath, password);
                }
                else
                {
                    tmp = new SevenZipExtractor(filePath);
                }
                if (fileExtractionStarted != null)
                {
                    tmp.FileExtractionStarted += fileExtractionStarted;
                }
                if (fileExists != null)
                {
                    tmp.FileExists += fileExists;
                }
                if (extracting != null)
                {
                    tmp.Extracting += extracting;
                }
                if (fileExtractionFinished != null)
                {
                    tmp.FileExtractionFinished += fileExtractionFinished;
                }
                tmp.ExtractArchive(extractFolder);
                tmp?.Dispose();
            }
            catch (Exception ex)
            {
                result = false;
                LogHelper.Error(ex, "7z解压缩文件异常");
            }
            return(result);
        }
        public ShellContent ExtractFile(ArchiveFileInfo file)
        {
            using (var extractor = new SevenZipExtractor(FilePath))
            {
                var content = new ArchiveFileContent(file);

                // unfortunately, the extractor doesn't seem to support a pull model.
                // so we push the data into memory first
                // we could also use a physical file as a temporary cache. it maybe better...
                extractor.ExtractFile(file.Index, content.Stream);

                // rewind
                content.Stream.Position = 0;
                return(content);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Extract a file to a path
        /// </summary>
        /// <param name="path"></param>
        /// <param name="extractor"></param>
        /// <param name="status"></param>
        private void TryExtractMod(string path, SevenZipExtractor extractor, DownloadStatus status)
        {
            status.Label.Invoke(
                (MethodInvoker)(() =>
            {
                status.Label.Text = @"Extracting Files...";
                status.ProgressBar.Step = -100;
                status.ProgressBar.PerformStep();
            }));

            extractor.Extracting += (sender, e) => Extractor_Extracting(sender, e, status);
            Mod.ArchivePath       = path;
            var folderPath = App.FactorioLoader.Config.ReserveFolder + "\\" + Mod.FolderName;

            ModFileHelper.Extract(extractor, folderPath);
        }
Ejemplo n.º 5
0
        public void ExtractionToStreamTest()
        {
            using (var tmp = new SevenZipExtractor(@"TestData\multiple_files.7z"))
            {
                using (var fileStream = new FileStream(Path.Combine(OutputDirectory, "streamed_file.txt"), FileMode.Create))
                {
                    tmp.ExtractFile(1, fileStream);
                }
            }

            Assert.AreEqual(1, Directory.GetFiles(OutputDirectory).Length);

            var extractedFile = Directory.GetFiles(OutputDirectory)[0];

            Assert.AreEqual("file2", File.ReadAllText(extractedFile));
        }
        public void CompressFile_WithSfnPath()
        {
            var compressor = new SevenZipCompressor
            {
                ArchiveFormat = OutArchiveFormat.Zip
            };

            compressor.CompressFiles(TemporaryFile, @"TESTDA~1\emptyfile.txt");
            Assert.IsTrue(File.Exists(TemporaryFile));

            using (var extractor = new SevenZipExtractor(TemporaryFile))
            {
                Assert.AreEqual(1, extractor.FilesCount);
                Assert.AreEqual("emptyfile.txt", extractor.ArchiveFileNames[0]);
            }
        }
        public async Task CompressDirectoryAsync()
        {
            var compressor = new SevenZipCompressor {
                DirectoryStructure = false
            };
            await compressor.CompressDirectoryAsync("TestData", TemporaryFile);

            Assert.IsTrue(File.Exists(TemporaryFile));

            using (var extractor = new SevenZipExtractor(TemporaryFile))
            {
                Assert.AreEqual(Directory.GetFiles("TestData").Length, extractor.FilesCount);
                Assert.IsTrue(extractor.ArchiveFileNames.Contains("zip.zip"));
                Assert.IsTrue(extractor.ArchiveFileNames.Contains("tar.tar"));
            }
        }
        public void TestRead()
        {
            var file = new FileInfo("TickDataV1_1");

            using (var stream = new MemoryStream())
                using (var fileStream = file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    using (var zip = new SevenZipExtractor(fileStream)) {
                        zip.ExtractFile(0, stream);
                        stream.Seek(0, SeekOrigin.Begin);
                        var serializer = new PbTickSerializer();
                        var codec      = new PbTickCodec();
                        foreach (var tick in serializer.Read(stream))
                        {
                        }
                    }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Gets all files referenced by this mod. This does not include moddessc.ini.
        /// </summary>
        /// <param name="archive">Archive, if this mod is in an archive.</param>
        /// <returns></returns>
        public List <string> GetAllRelativeReferences(SevenZipExtractor archive = null)
        {
            var references = new List <string>();

            //references.Add("moddesc.ini"); //Moddesc is implicitly referenced by the mod.
            //Replace or Add references
            foreach (var job in InstallationJobs)
            {
                foreach (var jobFile in job.FilesToInstall.Values)
                {
                    if (job.JobDirectory == @".")
                    {
                        references.Add(jobFile);
                    }
                    else
                    {
                        references.Add(job.JobDirectory + @"\" + jobFile);
                    }
                }
                foreach (var dlc in job.AlternateDLCs)
                {
                    if (dlc.AlternateDLCFolder != null)
                    {
                        var files = FilesystemInterposer.DirectoryGetFiles(FilesystemInterposer.PathCombine(IsInArchive, ModPath, dlc.AlternateDLCFolder), "*", SearchOption.AllDirectories, archive).Select(x => IsInArchive ? x : x.Substring(ModPath.Length + 1)).ToList();
                        references.AddRange(files);
                    }
                }
                foreach (var file in job.AlternateFiles)
                {
                    if (file.AltFile != null)
                    {
                        references.Add(file.AltFile);
                    }
                }

                foreach (var customDLCmapping in job.CustomDLCFolderMapping)
                {
                    references.AddRange(FilesystemInterposer.DirectoryGetFiles(FilesystemInterposer.PathCombine(IsInArchive, ModPath, customDLCmapping.Key), "*", SearchOption.AllDirectories, archive).Select(x => IsInArchive ? x : x.Substring(ModPath.Length + 1)).ToList());
                }
            }
            references.AddRange(AdditionalDeploymentFiles);
            foreach (var additionalDeploymentDir in AdditionalDeploymentFolders)
            {
                references.AddRange(FilesystemInterposer.DirectoryGetFiles(FilesystemInterposer.PathCombine(IsInArchive, ModPath, additionalDeploymentDir), "*", SearchOption.AllDirectories, archive).Select(x => IsInArchive ? x : x.Substring(ModPath.Length + 1)).ToList());
            }
            return(references);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// アーカイブ内から指定ファイルを削除する
        /// </summary>
        /// <param name="filename">削除するファイル名</param>
        /// <param name="archivePath">ファイルのあるアーカイブへのパス</param>
        public void Remove(string filename, string archivePath)
        {
            Dictionary <int, string> filesToDelete;

            using (var extractor = new SevenZipExtractor(archivePath))
                filesToDelete = extractor.ArchiveFileData.Where(file => file.FileName == filename)
                                .ToDictionary(file => file.Index, _ => (string)null);

            if (!filesToDelete.Any())
            {
                return;
            }

            var compressor = CreateCompressor();

            compressor.ModifyArchive(archivePath, filesToDelete);
        }
Ejemplo n.º 11
0
        static int Main(string[] args)
        {
            SevenZipExtractor.SetLibraryPath(
                Path.Combine(Path.GetDirectoryName(typeof(SevenZipProgram).Assembly.Location), "7z.dll"));
            var filedir = args.FirstOrDefault(x => !x.StartsWith("-"));

            if (filedir == null)
            {
                Console.WriteLine("Must specify a file.");
                return(1);
            }

            Console.WriteLine("64bit process: " + Environment.Is64BitProcess);

            if (Directory.Exists(filedir))
            {
                filedir = filedir.TrimEnd('\\') + Path.DirectorySeparatorChar;
            }

            Console.CancelKeyPress += Console_CancelKeyPress;
            Archive.ConsoleExit.Setup((type) =>
            {
                cleanup();
                cancel = true;
                return(true);
            });

            new Thread(() =>
            {
                var myfs = new MyMirror(filedir);
                mounts.Add("X:");
                try
                {
                    myfs.Mount("X:", DokanOptions.NetworkDrive, 8, new NullLogger());
                } catch { }
            }).Start();

            while (!cancel)
            {
                Thread.Sleep(500);
            }

            cleanup();

            return(0);
        }
Ejemplo n.º 12
0
        private void ExtractFirst()
        {
            if (TotalFiles == 0)
            {
                return;
            }
            var tempFile = GetFileFromUnorderedIndex(0);

            if (File.Exists(tempFile))
            {
                return;
            }
            using var fileStream = File.OpenWrite(tempFile);
            var rarExtractor = new SevenZipExtractor(ContainerPath);

            rarExtractor.ExtractFile(FileNames[0], fileStream);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// 解压
        /// </summary>
        /// <param name="data">数据,需要解压的内容</param>
        /// <returns></returns>
        public byte[] Decompress(byte[] data)
        {
            byte[] result;
            using (MemoryStream compressedStream = new MemoryStream(data))
            {
                using (MemoryStream uncompressedStream = new MemoryStream())
                {
                    using (SevenZipExtractor extractor = new SevenZipExtractor(compressedStream))
                    {
                        extractor.ExtractFile(0, uncompressedStream);
                        result = uncompressedStream.ToArray();
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 14
0
        } // загрузка завершена

        void InstallProgress()
        {
            try
            {
                progressBar1.Maximum = 100;
                string fileName = varPath.Launcherfolder + "install.7z";
                var    extr     = new SevenZipExtractor(fileName);
                progressBar1.Invoke(new Action(() => progressBar1.Maximum = (int)extr.FilesCount));
                extr.FileExtractionStarted += Extr_FileExtractionStarted;
                extr.ExtractionFinished    += Extr_ExtractionFinishedInstall;
                extr.BeginExtractArchive(Environment.CurrentDirectory);
            }
            catch (Exception error)
            {
                MessageBox.Show(error.ToString());
            }
        } // начинает распаковку
Ejemplo n.º 15
0
        private Stream ExtractEntry(SevenZipExtractor zip, ArchiveFileInfo?entry)
        {
            if (entry != null && zip != null)
            {
                var memoryStream = new MemoryStream();

                ArchiveFileInfo entryValue = entry.GetValueOrDefault();

                if (entryValue != null)
                {
                    zip.ExtractFile(entryValue.Index, memoryStream);
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    return(memoryStream);
                }
            }
            return(null);
        }
Ejemplo n.º 16
0
 /// <summary>
 /// release the given extracor
 /// </summary>
 /// <param name="extractor"></param>
 public void ReleaseExtractor(SevenZipExtractor extractor)
 {
     try
     {
         if (extractor != null)
         {
             extractor.Dispose();
             extractor = null;
         }
     }
     catch (Exception err)
     {
     }
     finally
     {
     }
 }
        public void CompressDirectory_WithSfnPath()
        {
            var compressor = new SevenZipCompressor
            {
                ArchiveFormat         = OutArchiveFormat.Zip,
                PreserveDirectoryRoot = true
            };

            compressor.CompressDirectory("TESTDA~1", TemporaryFile);
            Assert.IsTrue(File.Exists(TemporaryFile));

            using (var extractor = new SevenZipExtractor(TemporaryFile))
            {
                Assert.AreEqual(1, extractor.FilesCount);
                Assert.IsTrue(extractor.ArchiveFileNames[0].StartsWith("TestData_LongerDirectoryName", StringComparison.OrdinalIgnoreCase));
            }
        }
Ejemplo n.º 18
0
 private void button6_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         string sevenzPath = startupPath + "\\zip\\7z.dll";
         SevenZipExtractor.SetLibraryPath(sevenzPath);
         SevenZipCompressor tmp = new SevenZipCompressor();
         tmp.ArchiveFormat    = OutArchiveFormat.Zip;
         tmp.CompressionLevel = CompressionLevel.Normal;
         tmp.CompressDirectory(@"c:\Thomas\Gekko\GekkoCS\", @"c:\Thomas\Gekko\" + GetVersion() + ".zip", true);
         MessageBox.Show("Zipping of Gekko " + GetVersion() + ".zip" + "  ok -- REMOVE .git and TestResults folders!");
     }
     catch
     {
         MessageBox.Show("*** ERROR: Zipping of Gekko source failed");
     }
 }
Ejemplo n.º 19
0
 private void button4_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         string sevenzPath = startupPath + "\\zip\\7z.dll";
         SevenZipExtractor.SetLibraryPath(sevenzPath);
         SevenZipCompressor tmp = new SevenZipCompressor();
         tmp.ArchiveFormat    = OutArchiveFormat.Zip;
         tmp.CompressionLevel = CompressionLevel.Normal;
         tmp.CompressDirectory(@"c:\Program Files (x86)\Gekko\", @"c:\tmp\Gekko_files\Gekko.zip", true);
         MessageBox.Show("Zipping of Gekko program dir ok");
     }
     catch
     {
         MessageBox.Show("*** ERROR: Zipping of Gekko program dir failed");
     }
 }
Ejemplo n.º 20
0
        /// <summary>
        /// self uncompress a content to BitmapImage
        /// </summary>
        /// <param name="inputFile"></param>
        /// <returns></returns>
        public BitmapImage UncompressToBitmapImage(string inputFile, FolderComicsInfo info, String DirectoryPath)
        {
            SevenZipExtractor temp = null;

            try
            {
                temp = GetExtractor(inputFile);
                BitmapImage            bitmap      = null;
                List <ArchiveFileInfo> list        = temp.ArchiveFileData.OrderBy(f => f.FileName).ToList();
                ArchiveFileInfo        filenamepng =
                    list.Where(f => (f.FileName.EndsWith(".jpg") || f.FileName.EndsWith(".png")) &&
                               (f.FileName.Contains("MACOSX") == false) &&
                               (f.Size > 0) &&
                               (f.IsDirectory == false)).FirstOrDefault();
                using (MemoryStream ms = new MemoryStream())
                {
                    temp.ExtractFile(filenamepng.Index, ms);
                    bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    ms.Position = 0;
                    ms.Seek(0, SeekOrigin.Begin);
                    bitmap.DecodePixelHeight = 384;
                    bitmap.DecodePixelWidth  = 256;
                    bitmap.CacheOption       = BitmapCacheOption.OnLoad;
                    bitmap.StreamSource      = ms;
                    bitmap.EndInit();
                    bitmap.Freeze();

                    //Save image for test
                    //String path = DirectoryPath +  "\\snap"+System.IO.Path.GetExtension(filenamepng);
                    //Save(bitmap,path);

                    return(bitmap);
                }
                return(bitmap);
            }
            catch (Exception err)
            {
                var bmp = new BitmapImage();
                return(bmp);
            }
            finally
            {
                ReleaseExtractor(temp);
            }
        }
Ejemplo n.º 21
0
        private void ExtractFile(SevenZipExtractor extractor, ManifestFile file)
        {
            using (var destFileStream = new FileStream(file.InstallPath, FileMode.Create, FileAccess.Write))
            {
                try
                {
                    extractor.ExtractFile(file.File, destFileStream);
                }
                catch (Exception exception)
                {
                    this.errorLogger.Log(exception);
                }

                destFileStream.Flush();
                destFileStream.Close();
            }
        }
Ejemplo n.º 22
0
        public void Download(string url, string version)
        {
            // Windows will throw an error if you have the folder you're trying to delete open in
            // explorer. It will remove the contents but error out on the folder removal. That's
            // good enough but this is just so it doesn't crash.
            try
            {
                if (Directory.Exists(@"dolphin"))
                {
                    Directory.Delete(@"dolphin", true);
                }
            }
            catch (IOException)
            {
            }

            using (WebClient client = new WebClient())
            {
                client.DownloadProgressChanged += (s, e) =>
                {
                    UpdateProgress(e.ProgressPercentage, "Downloading build", ProgressBarStyle.Continuous);
                };
                client.DownloadFileAsync(new Uri(url), "dolphin.7z");

                while (client.IsBusy)
                {
                    Application.DoEvents();
                }

                SevenZipExtractor dolphin_zip = new SevenZipExtractor(@"dolphin.7z");

                dolphin_zip.Extracting += (sender, eventArgs) =>
                {
                    UpdateProgress(eventArgs.PercentDone, "Extracting and launching", ProgressBarStyle.Continuous);
                };

                try
                {
                    dolphin_zip.ExtractArchive("dolphin");
                }
                catch (Exception e)
                {
                    throw new Exception("Error extracting. Probably a missing build. Skipping this build.", e);
                }
            }
        }
Ejemplo n.º 23
0
        private void ExportToList(FileInfo file_input, FileInfo file_output, bool toCsv, bool toKdb, bool saveQuote)
        {
            // 都没选,跳过
            if (toCsv || toKdb)
            {
            }
            else
            {
                return;
            }

            Stream _stream = new MemoryStream();
            // 加载文件,支持7z解压
            var fileStream = file_input.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            {
                try
                {
                    using (var zip = new SevenZipExtractor(fileStream))
                    {
                        // 只解压了第0个,如果有多个也只解压第一个
                        zip.ExtractFile(0, _stream);
                        _stream.Seek(0, SeekOrigin.Begin);
                    }
                }
                catch
                {
                    _stream = fileStream;
                    _stream.Seek(0, SeekOrigin.Begin);
                }
            }

            PbTickCodec codec = new PbTickCodec();

            QuantBox.Data.Serializer.PbTickSerializer Serializer = new QuantBox.Data.Serializer.PbTickSerializer();
            List <PbTickView> list = Serializer.Read2View(_stream);

            if (toCsv)
            {
                ListToCSV(list, file_output);
            }
            // 得加入kdb+支持
            if (toKdb)
            {
                ListToKdb(list, saveQuote);
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Reads ticks from a Dukascopy binary buffer into a list
        /// </summary>
        /// <param name="symbol">The symbol</param>
        /// <param name="bytesBi5">The buffer in binary format</param>
        /// <param name="date">The date for the ticks</param>
        /// <param name="timeOffset">The time offset in milliseconds</param>
        /// <param name="pointValue">The price multiplier</param>
        private static unsafe List <Tick> AppendTicksToList(Symbol symbol, byte[] bytesBi5, DateTime date, int timeOffset, double pointValue)
        {
            var ticks = new List <Tick>();

            using (var inStream = new MemoryStream(bytesBi5))
            {
                using (var outStream = new MemoryStream())
                {
                    SevenZipExtractor.DecompressStream(inStream, outStream, (int)inStream.Length, null);

                    byte[] bytes = outStream.GetBuffer();
                    int    count = bytes.Length / DukascopyTickLength;

                    // Numbers are big-endian
                    // ii1 = milliseconds within the hour
                    // ii2 = AskPrice * point value
                    // ii3 = BidPrice * point value
                    // ff1 = AskVolume (not used)
                    // ff2 = BidVolume (not used)

                    fixed(byte *pBuffer = &bytes[0])
                    {
                        uint *p = (uint *)pBuffer;

                        for (int i = 0; i < count; i++)
                        {
                            ReverseBytes(p); uint time = *p++;
                            ReverseBytes(p); uint ask  = *p++;
                            ReverseBytes(p); uint bid  = *p++;
                            p++; p++;

                            if (bid > 0 && ask > 0)
                            {
                                ticks.Add(new Tick(
                                              date.AddMilliseconds(timeOffset + time),
                                              symbol,
                                              Convert.ToDecimal(bid / pointValue),
                                              Convert.ToDecimal(ask / pointValue)));
                            }
                        }
                    }
                }
            }

            return(ticks);
        }
Ejemplo n.º 25
0
 public void Decompress()
 {
     SevenZipExtractor.SetLibraryPath(System.IO.Path.Combine(Program.BaseDirectoryInternal, IntPtr.Size == 8 ? @"tools\7z64.dll" : @"tools\7z.dll"));
     foreach (var filename in DecompressPossible())
     {
         using (var szExtractor = new SevenZipExtractor(filename))
         {
             Debug.WriteLine("Decompressing " + filename);
             szExtractor.ExtractArchive(GamePath);
             foreach (var f in szExtractor.ArchiveFileNames)
             {
                 Command = Command.Replace(System.IO.Path.GetFileName(filename), f);
             }
         }
         File.Delete(filename);
     }
 }
Ejemplo n.º 26
0
 private void BtnExtraction_Click(object sender, EventArgs e)
 {
     if (txtExtractArchive.Text == "" && txtExtractDirectory.Text == "")
     {
         MessageBox.Show("Select your file please!", "Information");
     }
     else
     {
         SevenZipExtractor.SetLibraryPath(Application.StartupPath + "\\7z.dll");
         using (SevenZipExtractor tmp = new SevenZipExtractor(txtExtractArchive.Text))
         {
             tmp.ExtractArchive(txtExtractDirectory.Text);
         }
         MessageBox.Show("Extraction Finished ...", "Information");
         CleanTxtExtraction();
     }
 }
Ejemplo n.º 27
0
        public void ExtractionWithCancellationTest()
        {
            using (var tmp = new SevenZipExtractor(@"TestData\multiple_files.7z"))
            {
                tmp.FileExtractionStarted += (s, e) =>
                {
                    if (e.FileInfo.Index == 2)
                    {
                        e.Cancel = true;
                    }
                };

                tmp.ExtractArchive(OutputDirectory);

                Assert.AreEqual(2, Directory.GetFiles(OutputDirectory).Length);
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Method to Extract New DataBase
        /// </summary>
        public void ExtractNewDataBase()
        {
            if (File.Exists(Directory.GetParent(Parameter.Config.Paths.XmlDataBase) + "\\ADVANsCEne_NDScrc.xml.old"))
            {
                File.Delete(Directory.GetParent(Parameter.Config.Paths.XmlDataBase) + "\\ADVANsCEne_NDScrc.xml.old");
            }

            File.Move(Parameter.Config.Paths.XmlDataBase, Directory.GetParent(Parameter.Config.Paths.XmlDataBase) + "\\ADVANsCEne_NDScrc.xml.old");

            SevenZipExtractor.SetLibraryPath("7z.dll");
            SevenZipExtractor extract = new SevenZipExtractor(this.DatFileName);

            extract.ExtractArchive(Directory.GetParent(Parameter.Config.Paths.XmlDataBase).ToString());

            // ReloadAdvanSceneDataBase();
            File.Delete("ADVANsCEne_NDScrc.zip");
        }
Ejemplo n.º 29
0
 private void Wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e, string patchFile)
 {
     try
     {
         string fileName  = patchFile;
         string directory = AppDomain.CurrentDomain.BaseDirectory;
         var    extractor = new SevenZipExtractor(fileName);
         extractor.Extracting         += new EventHandler <ProgressEventArgs>(Extr_Extracting);
         extractor.ExtractionFinished += new EventHandler <EventArgs>(Extr_ExtractionFinished);
         extractor.BeginExtractArchive(directory);
         StatusLabel.Content = "Extracting patch file " + _downloadVersion + "...";
     }
     catch (Exception ex)
     {
         MessageBox.Show("Error extracting patch file." + Environment.NewLine + ex.Message + Environment.NewLine + ex.InnerException + Environment.NewLine + ex.StackTrace);
     }
 }
Ejemplo n.º 30
0
        public ePUB ParseFile(string filePath)
        {
            SevenZipExtractor temp = null;

            try
            {
                ePUB docPUB = new ePUB(filePath);

                temp = ZipHelper.Instance.GetExtractor(filePath);

                // find container.xml and parse it
                ArchiveFileInfo fil = temp.ArchiveFileData.Where(p => !p.IsDirectory && p.FileName == ePUBHelper.Files.ContainerRelativFile).First();
                using (MemoryStream stream = new MemoryStream())
                {
                    temp.ExtractFile(fil.FileName, stream);
                    ParseContainer(docPUB, stream);
                }

                // find OPF package file and parse it
                fil = temp.ArchiveFileData.Where(p => !p.IsDirectory && p.FileName == docPUB.Container.Package.SysRelativFilePath).First();
                using (MemoryStream stream = new MemoryStream())
                {
                    temp.ExtractFile(fil.FileName, stream);
                    ParsePackage(docPUB, stream);
                }

                // find the toc file and parse it
                fil = temp.ArchiveFileData.Where(p => !p.IsDirectory && p.FileName == docPUB.GetTOCFile()).First();
                using (MemoryStream stream = new MemoryStream())
                {
                    temp.ExtractFile(fil.FileName, stream);
                    ParseTOC(docPUB, stream);
                }

                return(docPUB);
            }
            catch (Exception err)
            {
                LogHelper.Manage("ePUBManager:ParseFile", err);
                return(null);
            }
            finally
            {
                ZipHelper.Instance.ReleaseExtractor(temp);
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Creates a mod index from a 7Zip file
        /// </summary>
        /// <param name="filename">Location of the 7Zip file.</param>
        /// <param name="miscFiles">Whether or not to include files that aren't related to mod installation. Default is false.</param>
        /// <returns>Structure containing mod info.</returns>
        public static Mod Index(string filename, bool miscFiles = false)
        {
            SevenZipExtractor z = new SevenZipExtractor(filename);

            var subfiles = new List<string>();
            foreach (var d in z.Files)
            {
                string s = d.Filename;
                if (!d.Attributes.HasFlag(Attributes.Directory) &&
                    (miscFiles ||
                    (s.StartsWith(@"AA2_MAKE\") ||
                    s.StartsWith(@"AA2_PLAY\"))))
                {
                    subfiles.Add(s);
                }
            }

            return new Mod(filename, z.UnpackedSize, subfiles);
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Injects mods as per selected in lsvMods.
        /// </summary>
        /// <param name="createBackup">Creates a backup of modified .pp files if true. Default is false.</param>
        /// <param name="checkConflicts">Checks for conflicts in pending mods. Default is true.</param>
        /// <param name="suppressPopups">If true, does not generate message boxes. Default is false.</param>
        public bool inject(bool createBackup = false, bool checkConflicts = true, bool suppressPopups = false)
        {
            initializeBench();
            cancelPending = false;
            updateStatus("Compiling changes...", LogIcon.Processing);

            //Compile changes
            _7z.ProgressUpdatedEventArgs updateProgress;
            List<string> rsub = new List<string>();
            List<Mod> mods = new List<Mod>();
            List<Mod> unmods = new List<Mod>();
            foreach (ListViewItem l in lsvMods.Items)
            {
                Mod m = (Mod)l.Tag;
                if (l.Checked != m.Installed)
                {
                    if (l.Checked)
                    {
                        mods.Add(m);
                    }
                    else
                    {
                        unmods.Add(m);
                        rsub.AddRange(m.SubFilenames);
                    }
                }
            }

            if (mods.Count + unmods.Count == 0)
            {
                updateStatus("No changes in selected mods found.", LogIcon.Error, false);
                updateStatus("FAILED: No changes in selected mods", LogIcon.Error, false, true);
                return false;
            }

            //Reset controls
            setEnabled(false);
            btnCancel.Enabled = true;
            prgMinor.Value = 0;
            prgMajor.Value = 0;
            int index = 0;

            Action Fail = () =>
            {
                setEnabled(true);
                prgMinor.Value = 0;
                prgMajor.Value = 0;
            };

            //Check if directory exists
            if (!(Directory.Exists(Paths.AA2Play) && Directory.Exists(Paths.AA2Edit)))
            {
                updateStatus("AA2Play/AA2Edit is not installed/cannot be found", LogIcon.Error, false);
                updateStatus("FAILED: AA2Play/AA2Edit is not installed/cannot be found", LogIcon.Error, false, true);
                Fail();
                return false;
            }
            
            refreshModList(true, txtSearch.Text);

            foreach (ListViewItem l in lsvMods.Items)
            {
                Mod m = (Mod)l.Tag;
                foreach (Mod n in mods)
                    if (n.Filename == m.Filename)
                        l.Checked = true;
                
                foreach (Mod n in unmods)
                    if (n.Filename == m.Filename)
                        l.Checked = false;
            }

            //Clear and create temp
            updateStatus("Clearing TEMP folder...");
            updateStatus("Clearing temporary folders...");

            if (Directory.Exists(Paths.TEMP))
                TryDeleteDirectory(Paths.TEMP);

            if (Directory.Exists(Paths.WORKING))
                TryDeleteDirectory(Paths.WORKING); 

            if (!Directory.Exists(Paths.BACKUP))
                Directory.CreateDirectory(Paths.BACKUP + @"\"); 

            
            Directory.CreateDirectory(Paths.TEMP + @"\");
            Directory.CreateDirectory(Paths.WORKING + @"\");
            Directory.CreateDirectory(Paths.TEMP + @"\AA2_PLAY\");
            Directory.CreateDirectory(Paths.TEMP + @"\AA2_MAKE\");
            Directory.CreateDirectory(Paths.TEMP + @"\BACKUP\");
            Directory.CreateDirectory(Paths.TEMP + @"\BACKUP\AA2_PLAY\");
            Directory.CreateDirectory(Paths.TEMP + @"\BACKUP\AA2_MAKE\");

            //Check conflicts
            if (checkConflicts) { 
                updateStatus("Checking conflicts...");

                Dictionary<string, List<Mod>> files = new Dictionary<string, List<Mod>>();

                foreach (Mod m in modDict.Values)
                    if (lsvMods.Items[m.Name].Checked)
                        m.SubFilenames.ForEach(x =>
                            {
                                if (files.ContainsKey(x))
                                    files[x].Add(m);
                                else
                                    files[x] = new List<Mod> { m };
                            }); //Set each subfile to their respective owner(s)

                bool conflict = false;

                foreach (ListViewItem item in lsvMods.Items) //Loop through list items
                {
                    if (!item.Checked) //We only care about ones that are / will be installed
                        continue;

                    Mod m = item.Tag as Mod; //The current mod we are checking

                    List<string> conflicts = files.Where(x => x.Value.Any(y => y.Name == m.Name)) //If the subfile is contained by the mod
                                                  .Where(x => x.Value.Count > 1) //If there is more than one owner
                                                  .Select(x => x.Key)
                                                  .ToList(); //Convert it to a list
                    

                    if (conflicts.Count > 0)
                    {
                        conflict = true;

                        foreach (string s in conflicts)
                            updateStatus(item.Text + ": " + s, LogIcon.Error, false);

                        item.BackColor = Color.FromArgb(255, 255, 160);
                    }
                }
                if (conflict)
                {
                    updateStatus("Collision detected.", LogIcon.Error, false);
                    updateStatus("FAILED: The highlighted mods have conflicting files", LogIcon.Error, false, true);
                    currentOwner.InvokeMessageBox("Some mods have been detected to have conflicting files.\nYou can use the log to manually fix the conflicting files in the mods (if they can be fixed) or you can proceed anyway by changing the relevant setting in the preferences.\nNote: if you proceed anyway, to uninstall you must uninstall mods in the reverse order you installed them to ensure that wrong files are not left behind.", "Collision detected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    Fail();
                    return false;
                }
            }

            //Check for free space

            long total7zSize = mods.Select(x => new SevenZipExtractor(x.Filename).UnpackedSize)
                                   .Sum(x => (long)x);

            long totalAA2PlaySize = mods.Select(x => new SevenZipExtractor(x.Filename).Files
                                            .Where(y => y.Filename.StartsWith("AA2_PLAY"))
                                            .Select(y => y.UnpackedSize))
                                        .Sum(x => x.Sum(y => (long)y));

            long totalAA2EditSize = mods.Select(x => new SevenZipExtractor(x.Filename).Files
                                            .Where(y => y.Filename.StartsWith("AA2_MAKE"))
                                            .Select(y => y.UnpackedSize))
                                        .Sum(x => x.Sum(y => (long)y));

            AdditionDictionary requiredSizes = new AdditionDictionary();

            requiredSizes[Paths.TEMP.Remove(1)] = total7zSize;

            if (Paths.TEMP.Remove(1) != Paths.AA2Edit.Remove(1))
                requiredSizes[Paths.AA2Edit.Remove(1)] = totalAA2EditSize + 0x40000000; //an approx. extra 1gb for temp files

            if (Paths.TEMP.Remove(1) != Paths.AA2Play.Remove(1))
                requiredSizes[Paths.AA2Play.Remove(1)] = totalAA2PlaySize + 0x40000000; //an approx. extra 1gb for temp files

            foreach (var kv in requiredSizes)
            {
                bool tryAgain = false;
                do
                {
                    tryAgain = false;
                    if (!IsEnoughFreeSpace(kv.Key, kv.Value))
                    {
                        updateStatus("FAILED: There is not enough free space", LogIcon.Error, false);

                        string spaces = requiredSizes.Select(x => "Drive " + x.Key + ":\\ : Required " + BytesToString(x.Value) + "; Available: " + BytesToString(new DriveInfo(kv.Key).AvailableFreeSpace))
                                        .Aggregate((a, b) => a + "\n" + b);
                        
                        var result = currentOwner.InvokeMessageBox("There is not enough free space to allow an approximate safe installation.\n" + spaces, "Not enough free space", MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation);

                        switch(result)
                        {
                            case DialogResult.Retry:
                                tryAgain = true;
                                break;
                            case DialogResult.Cancel:
                            default:
                                Fail();
                                return false;
                        }
                    }
                } while (tryAgain);
            }

            //Verify mods
            List<Mod> combined = mods.Concat(unmods).ToList();
            List<string> estPP = new List<string>();

            foreach (var m in combined)
            {
                SevenZipExtractor s;
                if (m.Installed)
                    s = new SevenZipExtractor(m.BackupFilename);
                else
                    s = new SevenZipExtractor(m.Filename);

                updateStatus("(" + index + "/" + combined.Count + ") Verifying " + m.Name + " (0%)...", LogIcon.Processing, false, true);

                foreach (var d in s.Files)
                {
                    if (d.Attributes.HasFlag(Attributes.Directory) && d.Filename.Length > 9)
                    {
                        string n = d.Filename.Remove(0, 9);

                        if (d.Filename.StartsWith("AA2_MAKE"))
                            estPP.Add(Paths.AA2Edit + @"\" + n + ".pp");
                        else
                            estPP.Add(Paths.AA2Play + @"\" + n + ".pp");
                    }
                }

                SevenZipBase.ProgressUpdatedEventArgs progress = (i) => {
                    this.prgMinor.GetCurrentParent().HybridInvoke(() => {
                        prgMinor.Value = i;
                    });
                    updateStatus("(" + index + "/" + combined.Count + ") Verifying " + m.Name + " (" + i + "%)...", LogIcon.Processing, false, true);
                };

                s.ProgressUpdated += progress;

                bool result = new Func<bool>(() => s.TestArchive()).SemiAsyncWait();

                s.ProgressUpdated -= progress;

                if (!result)
                {
                    updateStatus("FAILED: " + m.Name + " failed to verify.", LogIcon.Error, false);
                    Fail();
                    return false;
                }
            }

            //Verify PPs
            foreach (string p in estPP)
            {
                updateStatus("(" + index + "/" + combined.Count + ") Verifying " + p.Remove(0, p.LastIndexOf('\\') + 1) + "...", LogIcon.Processing);
                if (File.Exists(p))
                    if (!ppHeader.VerifyHeader(p))
                    {
                        updateStatus("FAILED: " + p.Remove(0, p.LastIndexOf('\\') + 1) + " failed to verify.", LogIcon.Error, false);
                        Fail();
                        return false;
                    }
            }

            //Extract all mods

            index = 0;

            string name = "";

            updateProgress = (i) => {
                prgMinor.GetCurrentParent().HybridInvoke(() => {
                    prgMinor.Value = i;
                });
                updateStatus("(" + index + "/" + combined.Count + ") Extracting " + name + " (" + i + "%)...", LogIcon.Processing, false, true);
            };

            _7z.ProgressUpdated += updateProgress;

            foreach (Mod item in combined)
            {
                index++;
                name = item.Name;
                updateStatus("(" + index + "/" + combined.Count + ") Extracting " + name + " (0%)...", LogIcon.Processing);

                if (mods.Contains(item))
                    _7z.Extract(item.Filename);
                else
                    _7z.Extract(item.BackupFilename, Paths.TEMP + @"\BACKUP\");

                prgMajor.Value = (100 * index / combined.Count);
                if (tryCancel())
                {
                    Fail();
                    return false;
                }
            }

            _7z.ProgressUpdated -= updateProgress;

            //Reached point of no return.
            btnCancel.Enabled = false;

            //Build ppQueue
            index = 0;
           
            Queue<basePP> ppQueue = new Queue<basePP>();
            List<basePP> ppList = new List<basePP>();
            updateStatus("Creating .pp file queue...");


            List<string> tempPLAY = new List<string>(Directory.GetDirectories(Paths.TEMP + @"\BACKUP\AA2_PLAY", "jg2*", SearchOption.TopDirectoryOnly));
            List<string> tempEDIT = new List<string>(Directory.GetDirectories(Paths.TEMP + @"\BACKUP\AA2_MAKE", "jg2*", SearchOption.TopDirectoryOnly));

            foreach (string path in tempPLAY)
            {
                ppQueue.Enqueue(new basePP(path, Paths.AA2Play));
            }
            foreach (string path in tempEDIT)
            {
                ppQueue.Enqueue(new basePP(path, Paths.AA2Edit));
            }

            //Prioritise removing subfiles from mods that are being uninstalled
            while (ppQueue.Count > 0)
            {
                basePP bp = ppQueue.Dequeue();

                var r = rsub.ToArray();
                foreach (string s in r)
                {
                    foreach (IWriteFile iw in bp.pp.Subfiles)
                        if (bp.ppDir + "\\" + iw.Name == s.Remove(0, 9))
                        {
                            rsub.Remove(s);
                            bp.pp.Subfiles.Remove(iw);
                            break;
                        }
                }

                prgMinor.Style = ProgressBarStyle.Continuous;
                int i = 1;

                foreach (string s in Directory.GetFiles(bp.ppRAW))
                {
                    string fname = s.Remove(0, s.LastIndexOf('\\') + 1);
                    foreach (IWriteFile sub in bp.pp.Subfiles)
                    {
                        if (fname == sub.Name)
                        {
                            bp.pp.Subfiles.Remove(sub);
                            break;
                        }
                    }
                    prgMinor.Value = (i * 100 / Directory.GetFiles(bp.ppRAW).Length);
                    bp.pp.Subfiles.Add(new Subfile(s));
                    i++;
                }

                ppList.Add(bp);
            }

            tempPLAY = new List<string>(Directory.GetDirectories(Paths.TEMP + @"\AA2_PLAY", "jg2*", SearchOption.TopDirectoryOnly));
            tempEDIT = new List<string>(Directory.GetDirectories(Paths.TEMP + @"\AA2_MAKE", "jg2*", SearchOption.TopDirectoryOnly));

            //Sort the uninstalled .pp files back into the main queue
            foreach (string path in tempPLAY)
            {
                var p = new basePP(path, Paths.AA2Play);
                var o = ppList.Find(x => x.ppDir == p.ppDir);
                if (o != null)
                {
                    p.pp = o.pp;
                    ppList.Remove(o);
                }
                ppQueue.Enqueue(p);
            }
            foreach (string path in tempEDIT)
            {
                var p = new basePP(path, Paths.AA2Edit);
                var o = ppList.Find(x => x.ppDir == p.ppDir);
                if (o != null)
                {
                    p.pp = o.pp;
                    ppList.Remove(o);
                }
                ppQueue.Enqueue(p);
            }

            int ii = 0;
            prgMajor.Value = 0;
            prgMinor.Value = 0;
            foreach (basePP b in ppList)
            {
                ii++;
                updateStatus("(" + ii + "/" + ppList.Count + ") Reverting " + b.ppFile + " (0%)...", LogIcon.Processing);
                if (b.pp.Subfiles.Count > 0)
                {
                    BackgroundWorker bb = b.pp.WriteArchive(b.pp.FilePath, createBackup);

                    bb.ProgressChanged += ((s, e) =>
                    {
                        prgMinor.GetCurrentParent().HybridInvoke(() => {
                            prgMinor.Value = e.ProgressPercentage;
                        });
                        updateStatus("(" + ii + "/" + ppList.Count + ") Reverting " + b.ppFile + " (" + e.ProgressPercentage + "%)...", LogIcon.Processing, false, true);
                    });

                    bb.SemiAsyncWait();
                }
                else
                {
                    File.Delete(b.pp.FilePath);
                }
                prgMajor.Value = (100 * ii / ppList.Count);
            }

            prgMinor.Value = 0;
            prgMajor.Value = 0;

            //Process .pp files
            int initial = ppQueue.Count;
            updateTaskbarProgress();
            index = 0;
            while (ppQueue.Count > 0)
            {
                basePP b = ppQueue.Dequeue();

                updateStatus("(" + (index + 1) + "/" + initial + ") Injecting " + b.ppFile + " (0%)...", LogIcon.Processing);

                prgMinor.Style = ProgressBarStyle.Continuous;
                int i = 1;

                foreach (Mod m in mods)
                {
                    foreach (string s in m.SubFilenames)
                    {
                        if (s.Contains(b.ppDir))
                        {
                            string r = s.Remove(0, 9);
                            string rs = r.Remove(0, r.LastIndexOf('\\') + 1);
                            string workingdir = Paths.WORKING + "\\BACKUP\\" + m.Name.Replace(".7z", "").Replace(".zip", "") + "\\";
                            string directory;
                            if (tempPLAY.Contains(b.ppRAW))
                            {
                                directory = workingdir + "AA2_PLAY\\" + r.Remove(r.LastIndexOf('\\') + 1);
                            }
                            else
                            {
                                directory = workingdir + "AA2_MAKE\\" + r.Remove(r.LastIndexOf('\\') + 1);
                            }

                            Directory.CreateDirectory(directory);
                            foreach (IWriteFile iw in b.pp.Subfiles)
                            {
                                if (iw.Name == rs)
                                {
                                    using (FileStream fs = new FileStream(directory + rs, FileMode.Create))
                                    {
                                        iw.WriteTo(fs);
                                    }
                                }
                            }
                        }
                    }
                }

                foreach (string s in rsub)
                {
                    foreach (IWriteFile iw in b.pp.Subfiles)
                        if (b.ppDir + "\\" + iw.Name == s.Remove(0, 9))
                        {
                            b.pp.Subfiles.Remove(iw);
                            break;
                        }
                }

                foreach (string s in Directory.GetFiles(b.ppRAW))
                {
                    string fname = s.Remove(0, s.LastIndexOf('\\')+1);
                    foreach (IWriteFile sub in b.pp.Subfiles)
                    {
                        if (fname == sub.Name)
                        {
                            b.pp.Subfiles.Remove(sub);
                            break;
                        }
                    }
                    prgMinor.Value = (100 * i / Directory.GetFiles(b.ppRAW).Length);
                    b.pp.Subfiles.Add(new Subfile(s));
                    i++;
                }
                if (b.pp.Subfiles.Count > 0)
                {
                    prgMinor.Value = 0;
                    BackgroundWorker bb = b.pp.WriteArchive(b.pp.FilePath, createBackup);

                    bb.ProgressChanged += ((s, e) =>
                    {
                        prgMinor.GetCurrentParent().HybridInvoke(() =>
                            { prgMinor.Value = e.ProgressPercentage; });
                        
                        updateStatus("(" + (index + 1) + "/" + initial + ") Injecting " + b.ppFile + " (" + e.ProgressPercentage + "%)...", LogIcon.Processing, false, true);
                    });

                    bb.SemiAsyncWait();
                }
                else
                {
                    File.Delete(b.pp.FilePath);
                }
                //Loop complete

                TryDeleteDirectory(b.ppRAW + "\\");

                index++;
                prgMajor.Value = (100 * index / initial);
                updateTaskbarProgress();
            }

            int ind = 0;
            //Archive backups
            prgMinor.Value = 0;
            prgMajor.Value = 0;
            if (!Directory.Exists(Paths.WORKING + "\\BACKUP\\")) { Directory.CreateDirectory(Paths.WORKING + "\\BACKUP\\"); }
            List<string> tempBackup = new List<string>(Directory.GetDirectories(Paths.WORKING + "\\BACKUP\\"));
            foreach (string s in tempBackup)
            {
                ind++;
                prgMajor.Value = (100 * ind / tempBackup.Count);
                updateStatus("(" + ind + "/" + tempBackup.Count + ") Archiving backup of " + s + " (0%)...", LogIcon.Processing);

                updateProgress = (i) => {
                    prgMinor.GetCurrentParent().HybridInvoke(() => {
                        prgMinor.Value = i;
                    });
                    updateStatus("(" + ind + "/" + tempBackup.Count + ") Archiving backup of " + s + " (" + i + "%)...", LogIcon.Processing, false, true);
                };

                _7z.ProgressUpdated += updateProgress;

                string item = s.Remove(0, s.LastIndexOf('\\') + 1);
                string archive = Paths.BACKUP + "\\" + item + ".7z";
                if (Directory.Exists(s + "\\AA2_PLAY\\"))
                {
                    foreach (string sub in Directory.GetDirectories(s + "\\AA2_PLAY\\"))
                    {
                        string g = sub.Remove(0, s.Length + 1) + "\\";
                        _7z.Compress(archive, s, g);
                    }
                }
                if (Directory.Exists(s + "\\AA2_MAKE\\"))
                {
                    foreach (string sub in Directory.GetDirectories(s + "\\AA2_MAKE\\"))
                    {
                        string g = sub.Remove(0, s.Length + 1) + "\\";
                        _7z.Compress(archive, s, g);
                    }
                }

                _7z.ProgressUpdated -= updateProgress;
            }

            //Finish up
            prgMinor.Style = ProgressBarStyle.Continuous;
            updateStatus("Finishing up...");
            mods.AddRange(unmods);

            foreach (Mod m in unmods)
            {
                string s = Paths.BACKUP + "\\" + m.Name.Replace(".zip", ".7z");
                if (File.Exists(s))
                {
                    tryDelete(s);
                }
            }

            Configuration.saveMods(modDict);

            TryDeleteDirectory(Paths.TEMP);
            TryDeleteDirectory(Paths.WORKING);

            updateStatus("Success!", LogIcon.OK, false);
            updateTaskbarProgress(TaskbarProgress.TaskbarStates.NoProgress);
            if (!suppressPopups)
                currentOwner.InvokeMessageBox("Mods successfully synced.");
            refreshModList();
            return true;
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Refreshes the list from the /mods/ directory.
        /// </summary>
        public void refreshModList(bool skipReload = false, string filter = "")
        {
            lsvMods.Items.Clear();
            ModDictionary modDict;
            if (!Configuration.loadMods(out modDict))
            {
                currentOwner.InvokeMessageBox("The configuration file has been detected as corrupt. Cache will be cleared.", "Corrupt configuration", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                FlushCache();
            }

            if (!skipReload)
            {
                setEnabled(false);
                initializeBench();
                
                string[] paths = getFiles(Paths.MODS, "*.7z|*.zip", SearchOption.TopDirectoryOnly);
                prgMinor.Style = ProgressBarStyle.Marquee;
            
                int i = 0;
            
                foreach (string path in paths)
                {
                    i++;
                    updateStatus("(" + i + "/" + paths.Length + ") Processing " + path.Remove(0, path.LastIndexOf('\\') + 1) + "...");

                    bool flag = false;
                    foreach (Mod m in modDict.Values)
                    {
                        if (path == m.Filename)
                        {
                            flag = true;
                            break;
                        }
                    }
                    if (flag)
                    {
                        prgMajor.Value = i;
                        continue;
                    }

                    modDict[path] = _7z.Index(path);

                    prgMajor.Value = (100 * i / paths.Length);
                }
            }

            foreach (Mod m in modDict.Values.ToList())
            {
                //bool backup = File.Exists(Paths.BACKUP + "\\" + m.Name.Remove(0, m.Name.LastIndexOf('\\') + 1).Replace(".zip", ".7z"));

                if (!File.Exists(m.Filename) && !m.Installed)
                {
                    modDict.Remove(m.Name);
                    continue;
                }

                Regex r = new Regex(@"^AA2_[A-Z]{4}\\");

                if (!m.Name.Replace(".7z", "").Replace(".zip", "").ToLower().Contains(filter.ToLower()) && filter != "")
                    continue;

                lsvMods.Items.Add(m.Name, m.Name.Replace(".7z", "").Replace(".zip", ""), 0);
                int index = lsvMods.Items.IndexOfKey(m.Name);

                if (m.Installed && !m.Exists)
                {
                    //lsvMods.Items[index].BackColor = Color.DarkBlue;
                }
                else if (!m.SubFilenames.Any(s => r.IsMatch(s)))
                {
                    List<string> sfiles;

                    SevenZipExtractor sz = new SevenZipExtractor(m.Filename);
                    sfiles = sz.Files.Select(s => s.Filename).ToList();

                    if (sfiles.Any(s => s.EndsWith(".7z") || s.EndsWith(".zip")))
                    {
                        lsvMods.Items[index].BackColor = Color.FromArgb(0xF7D088);
                        m.Properties["Status"] = "Actual mod 7z may be inside mod archive.";
                    }
                    else
                    {
                        lsvMods.Items[index].BackColor = Color.FromArgb(0xFFCCCC);
                        m.Properties["Status"] = "Not a valid mod.";
                    }
                }
                else if (m.Installed)
                {
                    lsvMods.Items[index].BackColor = Color.LightGreen;
                    lsvMods.Items[index].Checked = true;
                }

                m.Properties["Maximum Size"] = (m.Size / (1024)).ToString("#,## kB");

                if (m.Installed && m.InstallTime.Year > 2000)
                    m.Properties["Installed on"] = m.InstallTime.ToString();
                else
                    m.Properties.Remove("Installed on");

                lsvMods.Items[index].Tag = m;
                
                //modDict[m.Name] = m;
            }

            lsvMods.Sort();

            if (!skipReload)
            {
                Configuration.saveMods(modDict);

                prgMinor.Style = ProgressBarStyle.Continuous;

                prgMinor.Value = prgMinor.Maximum;
                updateStatus("Ready.", LogIcon.OK, false);


                setEnabled(true);
            }
        }
Ejemplo n.º 34
0
 public UnzipFileTestPak(string sevenZipFileFullPath)
 {
     var extractor =
         new SevenZipExtractor(File.OpenRead(sevenZipFileFullPath));
     extractor.ExtractArchive(DirectoryFullPath);
 }
Ejemplo n.º 35
0
        private static void SyncExtract(string filename, string wildcard, string dest = "")
        {
            if (dest == "")
                dest = Paths.TEMP;

            SevenZipExtractor z = new SevenZipExtractor(filename);

            z.ProgressUpdated += (i) =>
            {
                var invoke = ProgressUpdated;
                if (invoke != null)
                {
                    invoke(i);
                }
            };

            z.ExtractWildcard(dest + "\\", wildcard);
        }