Beispiel #1
0
        /// <summary>
        /// Verifies the client in a directory is extracted correctly.
        /// </summary>
        /// <param name="targetLocation">Location to verify.</param>
        /// <returns>Whether the extract was verified.</returns>
        public override bool Verify(string targetLocation)
        {
            // Get the archive entries.
            using var rarFile = RarArchive.Open(this.ArchiveFile);
            var archiveDirectory = Path.GetDirectoryName(rarFile.Entries.First(entry => Path.GetFileName(entry.Key).ToLower() == "legouniverse.exe").Key);

            // Verify the files exist and return false if a file is missing.
            foreach (var entry in rarFile.Entries)
            {
                // Return if the file is not in the parent directory of legouniverse.exe.
                // Some archives include other files that should not be looked at.
                if (!entry.Key.ToLower().StartsWith(archiveDirectory !.ToLower()) || entry.IsDirectory)
                {
                    continue;
                }

                // Determine the destination file path.
                var filePath = Path.Combine(targetLocation, Path.GetRelativePath(archiveDirectory, entry.Key));
                if (entry.Size == 0 || File.Exists(filePath))
                {
                    continue;
                }
                return(false);
            }

            // Return true (verified).
            return(true);
        }
Beispiel #2
0
 private void UnArch(Label label, ProgressBar progressBar)
 {
     using (var archive = RarArchive.Open(gamepath + "\\Archive.rar"))
     {
         foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
         {
             entry.WriteToDirectory(gamepath, new ExtractionOptions()
             {
                 ExtractFullPath = true,
                 Overwrite       = true
             });
         }
     }
     File.Delete(gamepath + "\\Archive.rar");
     MessageBox.Show("Dowload and installing complited.\nNow you have a game!");
     if (label.InvokeRequired && progressBar.InvokeRequired)
     {
         label.Invoke(new MethodInvoker(delegate
         {
             label.Visible = false;
         }));
         progressBar.Invoke(new MethodInvoker(delegate
         {
             progressBar.Visible = false;
             progressBar.Value   = 0;
         }));
     }
 }
Beispiel #3
0
        public static BoolWithMessage ExtractRarFile(string pathToRar, string extractPath)
        {
            try
            {
                Logger.Info($"extracting .rar {pathToRar} ...");


                using (RarArchive archive = RarArchive.Open(pathToRar))
                {
                    Logger.Info("... Opened .rar for read");

                    foreach (RarArchiveEntry entry in archive.Entries.Where(entry => !entry.IsDirectory))
                    {
                        Logger.Info($"...... extracting {entry.Key}");

                        entry.WriteToDirectory(extractPath, new ExtractionOptions()
                        {
                            ExtractFullPath = true,
                            Overwrite       = true
                        });

                        Logger.Info($"......... extracted!");
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Error(e);
                return(new BoolWithMessage(false, e.Message));
            }

            return(new BoolWithMessage(true));
        }
Beispiel #4
0
        /// <summary>
        /// Opens an Archive for random access
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="readerOptions"></param>
        /// <returns></returns>
        public static IArchive Open(Stream stream, ReaderOptions?readerOptions = null)
        {
            stream.CheckNotNull(nameof(stream));
            if (!stream.CanRead || !stream.CanSeek)
            {
                throw new ArgumentException("Stream should be readable and seekable");
            }
            readerOptions ??= new ReaderOptions();

            ArchiveType?type;

            IsArchive(stream, out type); //test and reset stream position

            if (type != null)
            {
                switch (type.Value)
                {
                case ArchiveType.Zip:
                    return(ZipArchive.Open(stream, readerOptions));

                case ArchiveType.SevenZip:
                    return(SevenZipArchive.Open(stream, readerOptions));

                case ArchiveType.GZip:
                    return(GZipArchive.Open(stream, readerOptions));

                case ArchiveType.Rar:
                    return(RarArchive.Open(stream, readerOptions));

                case ArchiveType.Tar:
                    return(TarArchive.Open(stream, readerOptions));
                }
            }
            throw new InvalidOperationException("Cannot determine compressed stream type. Supported Archive Formats: Zip, GZip, Tar, Rar, 7Zip, LZip");
        }
        public int GetEntriesCount()
        {
            switch (Type)
            {
            case ArchiveType.Rar:
                using (var archive = RarArchive.Open(FullName, ReaderOptions))
                    return(archive.Entries.Count);

            case ArchiveType.Zip:
                using (var archive = ZipArchive.Open(FullName, ReaderOptions))
                    return(archive.Entries.Count);

            case ArchiveType.Tar:
                using (var archive = TarArchive.Open(FullName, ReaderOptions))
                    return(archive.Entries.Count);

            case ArchiveType.SevenZip:
                using (var archive = SevenZipArchive.Open(FullName, ReaderOptions))
                    return(archive.Entries.Count);

            case ArchiveType.GZip:
                using (var archive = GZipArchive.Open(FullName, ReaderOptions))
                    return(archive.Entries.Count);

            default:
                throw new ArgumentOutOfRangeException(nameof(Type), Type, null);
            }
        }
        private static void InstallLITONE5()
        {
            Console.Out.WriteLine("Downloading LITONE5...");
            FileDownloader.DownloadFileFromURLToPath($"https://drive.google.com/uc?id=15JN3UUS2up8U80X-79nLFukVZamBwKjB", @"litone5.rar");

            Console.Out.WriteLine("Unzip LITONE5...");
            using (var archive = RarArchive.Open(@"litone5.rar"))
            {
                foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
                {
                    entry.WriteToDirectory(@"beatoraja0.6.1/skin", new ExtractionOptions()
                    {
                        ExtractFullPath = true,
                        Overwrite       = true
                    });
                }
            }

            FileDownloader.DownloadFileFromURLToPath($"https://drive.google.com/uc?id=1GB-pVfUlt36dXNUoTyQJLP7fSAfAz2-G", @"litone5_patch.rar");

            Console.Out.WriteLine("Unzip LITONE5 patch...");
            using (var archive = RarArchive.Open(@"litone5_patch.rar"))
            {
                foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
                {
                    entry.WriteToDirectory(@"beatoraja0.6.1/skin", new ExtractionOptions()
                    {
                        ExtractFullPath = true,
                        Overwrite       = true
                    });
                }
            }
        }
Beispiel #7
0
        public static IArchive Open(string filename, string password)
        {
            var archive = ArchiveFactory.Open(filename);

            if (password == null)
            {
                return(archive);
            }

            switch (archive.Type)
            {
            case ArchiveType.Rar:
                return(RarArchive.Open(filename, new ReaderOptions {
                    Password = password
                }));

            case ArchiveType.Zip:
                return(ZipArchive.Open(filename, new ReaderOptions {
                    Password = password
                }));

            case ArchiveType.Tar:
            case ArchiveType.SevenZip:
            case ArchiveType.GZip:
                throw new NotSupportedException(string.Format(ToolsStrings.ArchiveInstallator_UnsupportedEncryption, archive.Type));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        public static List <string> ExtractRarFile(string pathToRar, string extractPath, IProgress <double> progress = null)
        {
            List <string> filesExtracted = new List <string>();

            Logger.Info($"extracting .rar {pathToRar} ...");
            int entryCount   = 1;
            int currentCount = 0;

            using (RarArchive archive = RarArchive.Open(pathToRar))
            {
                Logger.Info("... Opened .rar for read");
                entryCount = archive.Entries.Count;

                foreach (RarArchiveEntry entry in archive.Entries.Where(entry => !entry.IsDirectory))
                {
                    Logger.Info($"...... extracting {entry.Key}");

                    entry.WriteToDirectory(extractPath, new ExtractionOptions()
                    {
                        ExtractFullPath = true,
                        Overwrite       = true
                    });

                    currentCount++;
                    progress?.Report((double)currentCount / (double)entryCount);
                    filesExtracted.Add(Path.Combine(extractPath, entry.Key));
                    Logger.Info($"......... extracted!");
                }
            }

            return(filesExtracted);
        }
Beispiel #9
0
        public static bool ReemplazarDatosDelMundo()
        {
            Console.WriteLine("Chequeando archivo rar del escritorio...");
            var filePath = Path.Combine(GetDesktopPath(), "GinkgoBilobaValheim.rar");
            var exists   = File.Exists(filePath);

            if (!exists)
            {
                Console.WriteLine("No hay ningun archivo .rar con el nombre de 'GinkgoBilobaValheim' en el escritorio");
                return(false);
            }
            Console.WriteLine("Archivo encontrado");
            try
            {
                Console.WriteLine("Reemplazando archivos del mundo...");
                using (var archive = RarArchive.Open(Path.Combine(GetDesktopPath(), "GinkgoBilobaValheim.rar")))
                {
                    foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
                    {
                        entry.WriteToDirectory(GetWordPath(), new ExtractionOptions()
                        {
                            ExtractFullPath = true,
                            Overwrite       = true
                        });
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error! " + ex.Message);
                return(false);
            }
        }
Beispiel #10
0
        //Extract the 2nd file in a solid archive to check that the first file is skipped properly
        private void DoRar_IsSolidEntryStreamCheck(string filename)
        {
            using (var stream = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, filename)))
            {
                using (var archive = RarArchive.Open(stream))
                {
                    Assert.True(archive.IsSolid);
                    IArchiveEntry[] entries = archive.Entries.Where(a => !a.IsDirectory).ToArray();
                    Assert.NotInRange(entries.Length, 0, 1);
                    Assert.False(entries[0].IsSolid); //first item in a solid archive is not marked solid and is seekable
                    IArchiveEntry testEntry = entries[1];
                    Assert.True(testEntry.IsSolid);   //the target. The non seekable entry

                    //process all entries in solid archive until the one we want to test
                    foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
                    {
                        using (CrcCheckStream crcStream = new CrcCheckStream((uint)entry.Crc)) //use the 7zip CRC stream for convenience (required a bug fix)
                        {
                            using (Stream eStream = entry.OpenEntryStream())                   //bug fix in RarStream to report the correct Position
                                eStream.CopyTo(crcStream);
                        } //throws if not valid
                        if (entry == testEntry)
                        {
                            break;
                        }
                    }
                }
            }
        }
Beispiel #11
0
 static void Main(string[] args)
 {
     using (Stream stream = File.OpenRead("ar.rar"))
         using (var archive = RarArchive.Open(stream, new ReaderOptions()
         {
             Password = "******",
             LeaveStreamOpen = true
         }))
         {
             foreach (var entry in archive.Entries)
             {
                 if (!entry.IsDirectory)
                 {
                     if (CompressionType.Rar == entry.CompressionType)
                     {
                         System.Console.WriteLine("Extention correct");
                     }
                     else
                     {
                         System.Console.WriteLine("Extention NOT correct!");
                     }
                     entry.WriteToDirectory(".", new ExtractionOptions()
                     {
                         ExtractFullPath = true,
                         Overwrite       = true
                     });
                 }
             }
         }
 }
Beispiel #12
0
        private void Form1_Load(object sender, EventArgs e)
        {
            string[] arguments        = Environment.GetCommandLineArgs();
            string   argumentinstring = string.Join(", ", arguments);



            if (argumentinstring.EndsWith(@".zip"))
            {
                using (var archive = ZipArchive.Open(argumentinstring.Substring(argumentinstring.IndexOf(',') + 1)))
                {
                    foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
                    {
                        entry.WriteToDirectory(Path.GetTempPath() + @"ZortosUnzipper", new ExtractionOptions()
                        {
                            ExtractFullPath = true,
                            Overwrite       = true
                        });
                    }
                }
                //ZipFile.ExtractToDirectory(argumentinstring.Substring(argumentinstring.IndexOf(',') + 1), Path.GetTempPath() + @"ZortosUnzipper");
                MessageBox.Show("Done File Extracted inside" + "\n" + Path.GetTempPath() + @"ZortosUnzipper");
                Dispose();
                Environment.Exit(0);
            }
            if (argumentinstring.EndsWith(".7z"))
            {
                using (var archive = SevenZipArchive.Open(argumentinstring.Substring(argumentinstring.IndexOf(',') + 1)))
                {
                    foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
                    {
                        entry.WriteToDirectory(Path.GetTempPath() + @"ZortosUnzipper", new ExtractionOptions()
                        {
                            ExtractFullPath = true,
                            Overwrite       = true
                        });
                    }
                }
                MessageBox.Show("Done File Extracted inside" + "\n" + Path.GetTempPath() + @"ZortosUnzipper");
                Dispose();
                Environment.Exit(0);
            }
            if (argumentinstring.EndsWith(".rar"))
            {
                using (var archive = RarArchive.Open(argumentinstring.Substring(argumentinstring.IndexOf(',') + 1)))
                {
                    foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
                    {
                        entry.WriteToDirectory(Path.GetTempPath() + @"ZortosUnzipper", new ExtractionOptions()
                        {
                            ExtractFullPath = true,
                            Overwrite       = true
                        });
                    }
                }
                MessageBox.Show("Done File Extracted inside:" + "\n" + Path.GetTempPath() + @"ZortosUnzipper");
                Dispose();
                Environment.Exit(0);
            }
        }
 /// <summary>
 /// Constructor with a FileInfo object to an existing file.
 /// </summary>
 /// <param name="fileInfo"></param>
 /// <param name="options"></param>
 public static IArchive Open(FileInfo fileInfo, ReaderOptions options = null)
 {
     fileInfo.CheckNotNull(nameof(fileInfo));
     options = options ?? new ReaderOptions {
         LeaveStreamOpen = false
     };
     using (var stream = fileInfo.OpenRead())
     {
         if (ZipArchive.IsZipFile(stream, null))
         {
             return(ZipArchive.Open(fileInfo, options));
         }
         stream.Seek(0, SeekOrigin.Begin);
         if (SevenZipArchive.IsSevenZipFile(stream))
         {
             return(SevenZipArchive.Open(fileInfo, options));
         }
         stream.Seek(0, SeekOrigin.Begin);
         if (GZipArchive.IsGZipFile(stream))
         {
             return(GZipArchive.Open(fileInfo, options));
         }
         stream.Seek(0, SeekOrigin.Begin);
         if (RarArchive.IsRarFile(stream, options))
         {
             return(RarArchive.Open(fileInfo, options));
         }
         stream.Seek(0, SeekOrigin.Begin);
         if (TarArchive.IsTarFile(stream))
         {
             return(TarArchive.Open(fileInfo, options));
         }
         throw new InvalidOperationException("Cannot determine compressed stream type. Supported Archive Formats: Zip, GZip, Tar, Rar, 7Zip");
     }
 }
        public void Rar_Multi_ArchiveStreamRead()
        {
            var testArchives = new string[] { "Rar.multi.part01.rar",
                                              "Rar.multi.part02.rar",
                                              "Rar.multi.part03.rar",
                                              "Rar.multi.part04.rar",
                                              "Rar.multi.part05.rar",
                                              "Rar.multi.part06.rar" };


            ResetScratch();
            using (var archive = RarArchive.Open(testArchives.Select(s => Path.Combine(TEST_ARCHIVES_PATH, s))
                                                 .Select(File.OpenRead)))
            {
                foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
                {
                    entry.WriteToDirectory(SCRATCH_FILES_PATH, new ExtractionOptions()
                    {
                        ExtractFullPath = true,
                        Overwrite       = true
                    });
                }
            }
            VerifyFiles();
        }
Beispiel #15
0
        /// <summary>
        /// создает правильно сформированную папку с файлами для архива
        /// </summary>
        /// <param name="correctNameOfFile"></param>
        /// <returns>путь, где лежит папка с файлами правильными</returns>
        static string CreateCorrectFolders(string correctNameOfFile)
        {
            Console.WriteLine("Создние времеменной папки для хранения правильного набора данных...");

            Directory.CreateDirectory(PathToSave + correctNameOfFile.Replace(".rar", ""));

            for (int i = 0; i < CorrectFoldersItem.Count - 1; i++)
            {
                Directory.CreateDirectory(PathToSave + correctNameOfFile.Replace(".rar", "") + "\\" + CorrectFoldersItem[i]);
            }

            RarArchive archive = RarArchive.Open(PathToLastFileInArchive); //добавили файлы из архива в поток

            foreach (RarArchiveEntry entry in archive.Entries)             // проходимся по ним в цикле и записываем в папку темп
            {
                string filename = Path.GetFileName(entry.FilePath);        //файл;

                if (entry.ToString().Contains(CorrectFoldersItem[0]))      //all_twn
                {
                    entry.WriteToFile(PathToSave + correctNameOfFile.Replace(".rar", "") + "\\" + CorrectFoldersItem[0] + "\\" + filename, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
                }
                else if (entry.ToString().Contains(CorrectFoldersItem[1]))//cl_cod
                {
                    entry.WriteToFile(PathToSave + correctNameOfFile.Replace(".rar", "") + "\\" + CorrectFoldersItem[1] + "\\" + filename, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
                }
                else//rgis.xml
                {
                    entry.WriteToFile(PathToSave + correctNameOfFile.Replace(".rar", "") + "\\" + filename, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
                }
            }

            return(PathToSave + correctNameOfFile.Replace(".rar", "") + "\\");
        }
 private void ReadRarPassword(string testArchive, string password)
 {
     ResetScratch();
     using (Stream stream = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, testArchive)))
         using (var archive = RarArchive.Open(stream, new ReaderOptions()
         {
             Password = password,
             LeaveStreamOpen = true
         }))
         {
             foreach (var entry in archive.Entries)
             {
                 if (!entry.IsDirectory)
                 {
                     Assert.Equal(CompressionType.Rar, entry.CompressionType);
                     entry.WriteToDirectory(SCRATCH_FILES_PATH, new ExtractionOptions()
                     {
                         ExtractFullPath = true,
                         Overwrite       = true
                     });
                 }
             }
         }
     VerifyFiles();
 }
 public string ExtractRARFile(string filePath, string UserID, int Fileid)
 {
     try
     {
         string[]   FileDetail = filePath.ToString().Split(new string[] { "\\", ".rar" }, StringSplitOptions.RemoveEmptyEntries);
         string     fileName   = FileDetail[FileDetail.Length - 1];
         string     newPath    = null;
         RarArchive file       = RarArchive.Open(filePath);
         newPath = Path.Combine(Server.MapPath("~/Files"), fileName);
         using (DBClass context = new DBClass())
         {
             context.AddParameter("@FileID", Fileid);
             context.AddParameter("@UserID", UserID);
             context.AddParameter("@FileName", fileName);
             context.AddParameter("@NewPath", newPath);
             context.ExecuteNonQuery("UpdateFileData", CommandType.StoredProcedure);
         }
         foreach (RarArchiveEntry rarFile in file.Entries)
         {
             rarFile.WriteToDirectory(newPath, ExtractOptions.ExtractFullPath);
         }
         //if(System.IO.File.Exists(filePath))
         //{
         //    System.IO.File.Delete(filePath);
         //}
         return(newPath);
     }
     catch (Exception e) { throw e; }
 }
Beispiel #18
0
        private bool ExtractZip(string path)
        {
            try
            {
                switch (Path.GetExtension(path).ToLower())
                {
                case ".7z":
                    using (var archive = SevenZipArchive.Open(path))
                    {
                        foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
                        {
                            entry.WriteToDirectory(Path.GetDirectoryName(path), new ExtractionOptions()
                            {
                                ExtractFullPath = true,
                                Overwrite       = true
                            });
                        }
                    }
                    break;

                case ".zip":
                    using (var archive = ZipArchive.Open(path))
                    {
                        foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
                        {
                            entry.WriteToDirectory(Path.GetDirectoryName(path), new ExtractionOptions()
                            {
                                ExtractFullPath = true,
                                Overwrite       = true
                            });
                        }
                    }
                    break;

                case ".rar":
                    using (var archive = RarArchive.Open(path))
                    {
                        foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
                        {
                            entry.WriteToDirectory(Path.GetDirectoryName(path), new ExtractionOptions()
                            {
                                ExtractFullPath = true,
                                Overwrite       = true
                            });
                        }
                    }
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                Error?.Invoke("Zip extraction failed: " + ex.Message);
                return(false);
            }

            return(true);
        }
Beispiel #19
0
 public static void rarFunction(List <ExtractFile> inputList)
 {
     // extract files
     foreach (var item in inputList)
     {
         try
         {
             using (var archive = RarArchive.Open(item.fileName))
             {
                 foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
                 {
                     entry.WriteToDirectory(item.fileDestination, new ExtractionOptions()
                     {
                         ExtractFullPath = true,
                         Overwrite       = true
                     });
                 }
             }
             using (FileStream fs = File.Create(item.filePath + @"\unrared"))
             {
                 logger.Info($"file: {item.fileName} unrared.");
             }
         }
         catch (Exception)
         {
             Console.WriteLine("fuckup");
             logger.Info($"file: {item.fileName} did not unrar, error.");
         }
     }
 }
Beispiel #20
0
 static void ExtractRar(string file)
 {
     try {
         //var tr = SharpCompress.Archives.Rar.RarArchive.Open(file);
         //using (var reader = tr.ExtractAllEntries())
         //{
         //    var options = new ExtractionOptions();
         //    options.ExtractFullPath = true;
         //    options.Overwrite = true;
         //    reader.WriteAllToDirectory(Path.GetDirectoryName(file), options);
         //}
         var filename = Path.GetFileNameWithoutExtension(file);
         var rars     = Directory.GetFiles(Path.GetDirectoryName(file), filename + ".r??").ToList()
                        .Where(f => !f.EndsWith(".rar")).OrderBy(x => x.ToString()).ToList();
         //var str = File.OpenRead
         //var reader = RarArchive.Open(file, new ReaderOptions { })
         List <Stream> streams = new List <Stream>();
         streams.Add(File.OpenRead(file));
         foreach (var f in rars)
         {
             streams.Add(File.OpenRead(f));
         }
         //using (Stream stream = File.OpenRead(file))
         //using (var reader = RarArchive.Open(streams))
         //{
         //    foreach(var entry in reader.Entries)
         //    {
         //        var curDir = Path.GetDirectoryName(file);
         //        Console.WriteLine("-> " + entry.Key);
         //        entry.WriteEntryToDirectory(curDir, new ExtractionOptions()
         //        {
         //            ExtractFullPath = true,
         //            Overwrite = true,
         //        });
         //    }
         //}
         using (var reader = RarArchive.Open(streams))
         {
             //using (var entries = reader. ExtractAllEntries())
             //{
             //    var options = new ExtractionOptions();
             //    options.ExtractFullPath = true;
             //    options.Overwrite = true;
             //    entries.WriteAllToDirectory(Path.GetDirectoryName(file), options);
             //}
         }
         Console.WriteLine($"extracted rar {file}");
         //delete rar files
         foreach (var rar in Directory.EnumerateFiles(Path.GetDirectoryName(file), filename + ".r??"))
         {
             Console.WriteLine($"Deleting rar file {rar}");
             File.Delete(rar);
         }
     }
     catch (Exception ex)
     {
         throw;
     }
 }
 private void DoRar_IsFirstVolume_False(string notFirstFilename)
 {
     using (var archive = RarArchive.Open(Path.Combine(TEST_ARCHIVES_PATH, notFirstFilename)))
     {
         Assert.True(archive.IsMultipartVolume());
         Assert.False(archive.IsFirstVolume());
     }
 }
 public void Rar_IsFirstVolume_False()
 {
     using (var archive = RarArchive.Open(Path.Combine(TEST_ARCHIVES_PATH, "Rar.multi.part03.rar")))
     {
         Assert.True(archive.IsMultipartVolume());
         Assert.False(archive.IsFirstVolume());
     }
 }
Beispiel #23
0
        public override List <FB2File> LoadFile(string fileName, IFB2ImportSettings settings)
        {
            var result = new List <FB2File>();

            try
            {
                RarArchive rarFile = RarArchive.Open(fileName);

                int n = rarFile.Entries.Count;
                Logger.Log.DebugFormat("Detected {0} entries in RAR file", n);
                foreach (var entry in rarFile.Entries)
                {
                    if (entry.IsDirectory)
                    {
                        Logger.Log.DebugFormat("{0} is not file but folder", fileName);
                        continue;
                    }
                    var extension = Path.GetExtension(entry.FilePath);
                    if (extension != null && extension.ToUpper() == ".FB2")
                    {
                        try
                        {
                            string tempPath = Path.GetTempPath();
                            entry.WriteToDirectory(tempPath);
                            if (FileTypeDetector.DetectFileType(tempPath) != FileTypeDetector.FileTypesEnum.FileTypeFB2)
                            {
                                Logger.Log.ErrorFormat("{0} is not FB2 file", entry.FilePath);
                                continue;
                            }
                            string fileNameOnly = Path.GetFileName(entry.FilePath);
                            Logger.Log.InfoFormat("Processing {0} ...", fileNameOnly);
                            var fb2Loader = new FB2FileLoader();
                            try
                            {
                                result.AddRange(fb2Loader.LoadFile(string.Format(@"{0}\{1}", tempPath, fileNameOnly), settings));
                            }
                            catch (Exception)
                            {
                                Logger.Log.ErrorFormat("Unable to load {0}", fileNameOnly);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Log.ErrorFormat("Unable to unrar file entry {0} : {1}", entry.FilePath, ex);
                        }
                    }
                    else
                    {
                        Logger.Log.InfoFormat("{0} is not FB2 file", entry.FilePath);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log.ErrorFormat("Error loading RAR file : {0}", ex);
            }
            return(result);
        }
Beispiel #24
0
        private async Task LoadCBRComic(StorageFile storageFile)
        {
            try
            {
                using (var zipStream = await storageFile.OpenStreamForReadAsync())
                    using (var memoryStream = new MemoryStream((int)zipStream.Length))
                    {
                        await zipStream.CopyToAsync(memoryStream);

                        memoryStream.Position = 0;

                        var rarArchive = RarArchive.Open(memoryStream);

                        if (rarArchive == null)
                        {
                            return;
                        }

                        var comic = new DisplayComic
                        {
                            File     = storageFile,
                            FullPath = storageFile.Name,
                            Name     = storageFile.DisplayName,
                            Pages    = rarArchive.Entries.Count
                        };

                        foreach (var entry in rarArchive.Entries)
                        {
                            if (IsValidEntry(entry))
                            {
                                continue;
                            }

                            using (var entryStream = new MemoryStream((int)entry.Size))
                            {
                                entry.WriteTo(entryStream);
                                entryStream.Position = 0;

                                using (var binaryReader = new BinaryReader(entryStream))
                                {
                                    var bytes = binaryReader.ReadBytes((int)entryStream.Length);

                                    comic.CoverageImageBytes = bytes;

                                    break;
                                }
                            }
                        }

                        comics.Add(comic);
                    }
            }
            catch (Exception ex)
            {
                // Do nothing
            }
        }
Beispiel #25
0
        /// <summary>指定されたエクセルブックファイルに含まれる画像を圧縮します。</summary>
        /// <param name="sourceFilePath">ファイルパス</param>
        /// <param name="targetInnerPath">処理対象内部パス</param>
        internal void QuantFromZipFile(string sourceFilePath, string targetInnerPath = "")
        {
            string reg = this.IsConvertToPng ? @"{0}.*\.png|{0}.*\.jpeg|{0}.*\.jpg|{0}.*\.bmp" : @"{0}.*\.png";

            reg = string.Format(reg, targetInnerPath);
            Regex regex = new Regex(reg);

            Console.WriteLine("減色を開始します:{0}", sourceFilePath);

            string distinationFileName = Path.GetFileNameWithoutExtension(sourceFilePath) + ".zip";

            string.Format(Properties.Settings.Default.FileNameTemplate, distinationFileName);
            string distinationFilePath = Path.GetDirectoryName(sourceFilePath);

            distinationFilePath = Path.Combine(distinationFilePath, distinationFileName);
            this.OutputFilePath = distinationFilePath;

            using (RarArchive archive = RarArchive.Open(sourceFilePath))
                using (ZipArchive distArchive = new ZipArchive(new FileStream(distinationFilePath, FileMode.Create, FileAccess.Write), ZipArchiveMode.Create))
                    using (PngQuant pngquant = new PngQuant())
                    {
                        foreach (RarArchiveEntry entry in archive.Entries)
                        {
                            if (regex.IsMatch(entry.Key.ToLower()) == false)
                            {
                                ZipArchiveEntry distEntry = distArchive.CreateEntry(entry.Key);
                                using (Stream srcStream = entry.OpenEntryStream())
                                    using (Stream distStream = distEntry.Open())
                                    {
                                        srcStream.CopyTo(distStream);
                                    }

                                continue;
                            }

                            // 解凍して一時ファイルを作成し、減色する
                            Stream tranStream;
                            using (Stream s = entry.OpenEntryStream())
                            {
                                tranStream = pngquant.Subtractive(s);
                            }

                            // 減色したファイルをブックに再設定
                            string distEntryName = PathUtils.ChangeExtension(entry.Key, ".png");
                            var    e             = distArchive.CreateEntry(distEntryName, CompressionLevel.NoCompression);
                            using (var stream = e.Open())
                            {
                                tranStream.CopyTo(stream);
                            }

                            Console.WriteLine("・{0}", entry.Key);

                            // 変換イベントを発生させる
                            this.FileNameChanged?.Invoke(this, new FileNameChangedEventArgs(entry.Key, distEntryName));
                        }
                    }
        }
Beispiel #26
0
 RarArchive FirstArchiveForFile(string filePath)
 {
     if (ValidateArchive(filePath))
     {
         RarArchive archive = RarArchive.Open(filePath);
         return(FirstArchiveForArchive(archive));
     }
     return(null);
 }
Beispiel #27
0
        public static void TestRar()
        {
            var archive = RarArchive.Open(@"C:\Code\sharpcompress\TestArchives\sharpcompress.rar");

            foreach (var entry in archive.Entries)
            {
                entry.WriteToDirectory(@"C:\temp");
            }
        }
        private RarArchive?GetRarArchive(FileEntry fileEntry, ExtractorOptions options)
        {
            RarArchive?rarArchive = null;

            try
            {
                rarArchive = RarArchive.Open(fileEntry.Content);
            }
            catch (Exception e)
            {
                Logger.Debug(Extractor.DEBUG_STRING, ArchiveFileType.RAR, fileEntry.FullPath, string.Empty, e.GetType());
            }
            var needsPassword = false;

            try
            {
                using var testStream = rarArchive.Entries.First().OpenEntryStream();
            }
            catch (Exception e)
            {
                needsPassword = true;
            }
            if (needsPassword is true)
            {
                var passwordFound = false;
                foreach (var passwords in options.Passwords.Where(x => x.Key.IsMatch(fileEntry.Name)))
                {
                    if (passwordFound)
                    {
                        break;
                    }
                    foreach (var password in passwords.Value)
                    {
                        try
                        {
                            fileEntry.Content.Position = 0;
                            rarArchive = RarArchive.Open(fileEntry.Content, new SharpCompress.Readers.ReaderOptions()
                            {
                                Password = password, LookForHeader = true
                            });
                            var count = 0; //To do something in the loop
                            foreach (var entry in rarArchive.Entries)
                            {
                                //Just do anything in the loop, but you need to loop over entries to check if the password is correct
                                count++;
                            }
                            break;
                        }
                        catch (Exception e)
                        {
                            Logger.Debug(Extractor.DEBUG_STRING, ArchiveFileType.RAR, fileEntry.FullPath, string.Empty, e.GetType());
                        }
                    }
                }
            }
            return(rarArchive);
        }
Beispiel #29
0
        public static void TestRar3()
        {
            var archive = RarArchive.Open(@"C:\Code\sharpcompress\TestArchives\sharpcompress2.part001.rar");

            foreach (var entry in archive.Entries)
            {
                Console.WriteLine(entry.FilePath);
                entry.WriteToDirectory(@"C:\temp", ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
            }
        }
Beispiel #30
0
 private void ReadRarArchive(string localPath)
 {
     using (RarArchive ra = RarArchive.Open(localPath))
     {
         foreach (RarArchiveEntry entry in ra.Entries)
         {
             PopulateSelfList(entry);
         }
     }
 }