internal static IEnumerable<RarArchiveEntry> GetEntries(RarArchive archive, IEnumerable<RarVolume> rarParts) { foreach (var groupedParts in GetMatchedFileParts(rarParts)) { yield return new RarArchiveEntry(archive, groupedParts); } }
RarArchive FirstArchiveForArchive(RarArchive archive) { if (!archive.IsFirstVolume()) { return archive; } if (!archive.IsFirstVolume()) { return FirstArchiveForVolumes(archive.Volumes); } return null; }
/// <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"); } if (readerOptions == null) { 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 async Task <bool> Load(bool fullBase, DirectoryInfo destinationDir) { string tempPath = Path.Combine(destinationDir.FullName, "fias_dbf_" + ((fullBase) ? "":"delta_") + DateTime.Now.ToShortDateString() + ".rar"); try { webClient.DownloadFile((fullBase ? FullUri : DeltaUri), tempPath); using (RarArchive archive = RarArchive.Open(tempPath)) { foreach (RarArchiveEntry item in archive.Entries) { item.WriteToDirectory(destinationDir.FullName); } } File.Delete(tempPath); return(true); } catch (Exception e) { Logger.Logger.Error(e.Message); return(false); } }
public static bool UnRar(Stream stream, string destination, bool ExtractFullPath = true, bool Overwrite = true, bool PreserveFileTime = true) { try { destination = PrepareDirectory(destination); var options = new ExtractionOptions { ExtractFullPath = ExtractFullPath, Overwrite = Overwrite, PreserveFileTime = PreserveFileTime }; using (var archive = RarArchive.Open(stream)) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { entry.WriteToDirectory(destination, options); } } return(true); } catch (Exception ex) { Logger.Instance.Error(ex.Message); return(false); } }
public void Rar_Jpg_ArchiveStreamRead() { ResetScratch(); using (var stream = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "Rarjpeg.jpg"))) { using (var archive = RarArchive.Open(stream, new ReaderOptions() { LookForHeader = true })) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { entry.WriteToDirectory(SCRATCH_FILES_PATH, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } VerifyFiles(); } }
/// <summary> /// Author: Johnny Wong /// Time: 2018.01.08 /// 解压rar文件到指定目录(带进度条) /// </summary> /// <param name="file">rar文件</param> /// <param name="folder">目录</param> /// <param name="pb">进度条</param> protected static void RarUncompress(string file, string folder, ProgressBar pb) { using (var archive = RarArchive.Open(file)) { pb.Invoke(new Action(() => { pb.Maximum = archive.Entries.Count(entry => !entry.IsDirectory); })); foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { entry.WriteToDirectory(folder, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); pb.Invoke(new Action(() => { try { pb.Value++; } catch (Exception) { } })); } } }
private static bool ExtractAVDump() { try { using (var archive = RarArchive.Open(avdumpRarDestination)) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { entry.WriteToDirectory(destination, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } File.Delete(avdumpRarDestination); } catch { return(false); } return(true); }
public ArchiveTypes IsArchive(string path) { var type = ArchiveTypes.None; if (RarArchive.IsRarFile(path)) { type = ArchiveTypes.RAR; } if (ZipArchive.IsZipFile(path)) { type = ArchiveTypes.Zip; } if (SevenZipArchive.IsSevenZipFile(path)) { type = ArchiveTypes.SevenZip; } if (TarArchive.IsTarFile(path)) { type = ArchiveTypes.Deflate; } return(type); }
public async Task <GetImagesFromArchiveResult> GetImagesFromRarFileAsync(StorageFile file) { CompositeDisposable disposables = new CompositeDisposable(); var stream = await file.OpenStreamForReadAsync() .AddTo(disposables); var rarArchive = RarArchive.Open(stream) .AddTo(disposables); var supportedEntries = rarArchive.Entries .Where(x => SupportedFileTypesHelper.IsSupportedImageFileExtension(x.Key)) .OrderBy(x => x.Key) .Select(x => (IImageSource) new ArchiveEntryImageSource(x, file, _recyclableMemoryStreamManager)) .ToArray(); return new GetImagesFromArchiveResult() { ItemsCount = (uint)supportedEntries.Length, Disposer = disposables, Images = supportedEntries, }; }
public static string Exact(string path) { if (!File.Exists(path)) { return(string.Empty); } var outputDirectory = Path.GetDirectoryName(path); var targetDir = outputDirectory + "\\" + Path.GetFileNameWithoutExtension(path); using (var archive = RarArchive.Open(path)) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { entry.WriteToDirectory(outputDirectory, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } return(targetDir); }
public static BoolWithMessage ExtractRarFile(string pathToRar, string extractPath) { try { using (RarArchive archive = RarArchive.Open(pathToRar)) { foreach (RarArchiveEntry entry in archive.Entries.Where(entry => !entry.IsDirectory)) { entry.WriteToDirectory(extractPath, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } } catch (Exception e) { return(new BoolWithMessage(false, e.Message)); } return(new BoolWithMessage(true)); }
public IArchive GetReadableArchive() { switch (Type) { case ArchiveType.Zip: return(ZipArchive.Open(FileInfo)); case ArchiveType.Tar: return(TarArchive.Open(FileInfo)); case ArchiveType.GZip: return(GZipArchive.Open(FileInfo)); case ArchiveType.Rar: return(RarArchive.Open(FileInfo)); case ArchiveType.SevenZip: return(SevenZipArchive.Open(FileInfo)); default: throw new ArgumentOutOfRangeException(nameof(Type), Type, null); } }
private void extractSubs(RarArchive archive, string outputDir) { try { string outputSubsDir = outputDir + @"\" + "Subs"; Directory.CreateDirectory(outputSubsDir); extractArchiveSingleThread(archive, outputSubsDir); // Extract rar file within rar file is present string[] rarSubs2 = Directory.GetFiles(outputSubsDir, "*.rar"); if (rarSubs2.Length > 0) { archive = RarArchive.Open(@rarSubs2[0]); extractArchiveSingleThread(archive, outputSubsDir); File.SetAttributes(rarSubs2[0], FileAttributes.Normal); File.Delete(rarSubs2[0]); } } catch (Exception ex) { MessageBox.Show("Subs Error: " + ex.Message); } }
/// <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, Options options) { fileInfo.CheckNotNull("fileInfo"); using (var stream = fileInfo.OpenRead()) { if (ZipArchive.IsZipFile(stream, null)) { stream.Dispose(); return(ZipArchive.Open(fileInfo, options, null)); } stream.Seek(0, SeekOrigin.Begin); if (TarArchive.IsTarFile(stream)) { stream.Dispose(); return(TarArchive.Open(fileInfo, options)); } stream.Seek(0, SeekOrigin.Begin); if (SevenZipArchive.IsSevenZipFile(stream)) { stream.Dispose(); return(SevenZipArchive.Open(fileInfo, options)); } stream.Seek(0, SeekOrigin.Begin); if (GZipArchive.IsGZipFile(stream)) { stream.Dispose(); return(GZipArchive.Open(fileInfo, options)); } stream.Seek(0, SeekOrigin.Begin); if (RarArchive.IsRarFile(stream, Options.LookForHeader | Options.KeepStreamsOpen)) { stream.Dispose(); return(RarArchive.Open(fileInfo, options)); } throw new InvalidOperationException("Cannot determine compressed stream type. Supported Archive Formats: Zip, GZip, Tar, Rar, 7Zip"); } }
/// <summary> /// Позволяет разархивировать zip и rar /// </summary> /// <param name="pathFrom">От куда брать архив</param> /// <param name="pathTo">Куда разархивировать</param> public static void ExtractArchive(string pathFrom, string pathTo) { DirectoryInfo dirFrom = new DirectoryInfo(pathFrom); DirectoryInfo dirTo = new DirectoryInfo(pathTo); FileInfo[] files = dirFrom.GetFiles(); // for (int i = 0; i < files.Length; i++) { string _pathFrom = pathFrom + "\\" + files[i].Name; if (files[i].Name.Contains(".zip")) { if (dirTo.Exists) { dirTo.Delete(true); // Разархивация .zip ZipFile.ExtractToDirectory(_pathFrom, pathTo); } else { dirTo.Create(); // Разархивация .zip ZipFile.ExtractToDirectory(_pathFrom, pathTo); } } else if (files[i].Name.Contains(".rar")) { if (dirTo.Exists) { dirTo.Delete(true); } // Разархивация .rar (ExtractOptions.ExtractFullPath) позволяет разархивировать и папки тоже RarArchive.WriteToDirectory(_pathFrom, pathTo, ExtractOptions.ExtractFullPath); } } }
/// <summary> /// Extracts the client in an archive to a directory. /// </summary> /// <param name="targetLocation">Location to extract to</param> public override void ExtractTo(string targetLocation) { // Get the path of the client. using var rarFile = RarArchive.Open(this.ArchiveFile); var archiveDirectory = Path.GetDirectoryName(rarFile.Entries.First(entry => Path.GetFileName(entry.Key).ToLower() == "legouniverse.exe").Key); // Extract the files. var completedFiles = 0; this.ReportExtractingProgress(0); 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.GetRelativePath(archiveDirectory, entry.Key); var newPath = Path.Combine(targetLocation, filePath); var newParentPath = Path.GetDirectoryName(newPath); // Extract the file. if (newParentPath != null && !Directory.Exists(newParentPath)) { Directory.CreateDirectory(newParentPath); } entry.WriteToFile(newPath); // Report the progress. completedFiles += 1; this.ReportExtractingProgress(completedFiles / (float)rarFile.Entries.Count); } this.ReportExtractingProgress(1); }
public SqlDumpReader(string filePath) { string fileExtension = Path.GetExtension(filePath); switch (fileExtension.ToLower()) { case ".zip": zipArchive = ZipArchive.Open(filePath); ZipArchiveEntry firstZipArchiveEntry = zipArchive.Entries.First(); FileSize = firstZipArchiveEntry.Size; streamReader = new StreamReader(firstZipArchiveEntry.OpenEntryStream()); break; case ".rar": rarArchive = RarArchive.Open(filePath); RarArchiveEntry firstRarArchiveEntry = rarArchive.Entries.First(); FileSize = firstRarArchiveEntry.Size; streamReader = new StreamReader(firstRarArchiveEntry.OpenEntryStream()); break; case ".gz": gZipArchive = GZipArchive.Open(filePath); GZipArchiveEntry firstGZipArchiveEntry = gZipArchive.Entries.First(); FileSize = firstGZipArchiveEntry.Size; streamReader = new StreamReader(firstGZipArchiveEntry.OpenEntryStream()); break; case ".7z": sevenZipArchive = SevenZipArchive.Open(filePath); SevenZipArchiveEntry firstSevenZipArchiveEntry = sevenZipArchive.Entries.First(); FileSize = firstSevenZipArchiveEntry.Size; streamReader = new StreamReader(new PositioningStream(firstSevenZipArchiveEntry.OpenEntryStream())); break; default: FileSize = new FileInfo(filePath).Length; streamReader = new StreamReader(filePath); break; } CurrentFilePosition = 0; }
/*[Fact] * public void Rar5_Encrypted_Archive() * { * ReadRarPassword("Rar5.encrypted_filesAndHeader.rar", "test"); * }*/ private void ReadRarPassword(string testArchive, string password) { 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(); }
// Code from https://github.com/adamhathcock/sharpcompress/blob/master/USAGE.md private static void ExtractRar(string pathTarget, string pathExtractTo) { using (var archive = RarArchive.Open(pathTarget)) { // Calculate the total extraction size. long totalSize = archive.TotalUncompressSize; //.Entries.Where(e => !e.IsDirectory).Sum(e => e.Size); long totalRead = 0; foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { // Update progress text GUI.ProgressText = ProgressText + entry.Key; entry.WriteToDirectory(pathExtractTo, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); // Track each individual extraction. totalRead += entry.Size; GUI.Progress = MainWindowViewModel.GetProgress(totalRead, totalSize); } } }
public Tuple <List <string>, string> Unrar(string location, string temp) { try { using (RarArchive archive = SharpCompress.Archives.Rar.RarArchive.Open(location)) { string specific = ""; List <string> filestodelete = new List <string>(); foreach (var entry in archive.Entries) { entry.WriteToFile(Path.Combine(temp + "\\", entry.Key), new ExtractionOptions() { Overwrite = true, ExtractFullPath = true }); if (entry.Key.ToUpper().Contains("EXE")) { if (Path.GetFileNameWithoutExtension(entry.Key) == Path.GetFileNameWithoutExtension(location)) { continue; } specific = entry.Key; } else { filestodelete.Add(entry.Key); } } return(new Tuple <List <string>, string>(filestodelete, specific)); } } catch { return(new Tuple <List <string>, string>(null, null)); } }
public bool Update() { string fromVersion = this.Version; try { this.fetchLatestReleaseBytes(); } catch (Exception e) { Console.WriteLine(e); } if (this.LatestReleaseFile == null) { return(false); } if (this.LatestReleaseFile.Length == 0) { return(false); } try { // write temp file var latestReleaseFileName = System.IO.Path.Combine(this.ModFullDirectory, this.LatestRelease.Assets[0].Name); System.IO.File.WriteAllBytes(latestReleaseFileName, this.LatestReleaseFile); // make backup var backupFileName = this.Name + "-" + (this.Version != "??" ? this.Version : DateTime.Now.Ticks.ToString()) + ".zip"; using (var archive = SharpCompress.Archives.Zip.ZipArchive.Create()) { archive.AddAllFromDirectory(this.ModFullDirectory); try { archive.SaveTo(Path.Combine(this.ModFullDirectory, backupFileName), new WriterOptions(CompressionType.Deflate)); } catch { // who cares } } //using (var backup = System.IO.Compression.ZipFile.Open(Path.Combine(this.ModFullDirectory, backupFileName), System.IO.Compression.ZipArchiveMode.Create)) //{ // var files = new DirectoryInfo(this.ModFullDirectory).EnumerateFiles(); // foreach (var file in files) // { // if (file.Name != backupFileName) // { // var entry = backup.CreateEntry(file.Name); // using (var stream = entry.Open()) // { // using (var filestream = file.OpenRead()) // { // while (filestream.Position != filestream.Length) // { // var fb = filestream.ReadByte(); // stream.WriteByte((byte)fb); // } // } // } // } // } //} if (latestReleaseFileName.ToLower().EndsWith(".zip")) { using (var archive = ZipArchive.Open(latestReleaseFileName)) { //archive.WriteToDirectory(this.ModFullDirectory,new ExtractionOptions() //{ // ExtractFullPath = true, // Overwrite = true //}); foreach (var entry in archive.Entries.Where(x => !x.IsDirectory)) { entry.WriteToDirectoryGP(this.ModFullDirectory, this.Name, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } //foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) //{ // entry. // System.IO.File.Delete(System.IO.Path.Combine(this.ModFullDirectory, entry.Key)); // entry.WriteToDirectory(this.ModFullDirectory, new ExtractionOptions() // { // ExtractFullPath = true, // Overwrite = true // }); //} } } else if (latestReleaseFileName.ToLower().EndsWith(".rar")) { using (var archive = RarArchive.Open(latestReleaseFileName)) { foreach (var entry in archive.Entries.Where(x => !x.IsDirectory)) { entry.WriteToDirectoryGP(this.ModFullDirectory, this.Name, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } } //using (var outZip = new FileStream(latestReleaseFileName, System.IO.FileMode.Open)) //{ // using (var zipArchive = new System.IO.Compression.ZipArchive(outZip, System.IO.Compression.ZipArchiveMode.Read)) // { // foreach (var entry in zipArchive.Entries) // { // if (entry.Name == "" && entry.Name != this.ModDirectory) // continue; // try // { // System.IO.File.Delete(System.IO.Path.Combine(this.ModFullDirectory, entry.Name)); // byte[] bytes = new byte[entry.Length]; // using (var stream = entry.Open()) // { // stream.Read(bytes, 0, (int)entry.Length); // } // System.IO.File.WriteAllBytes(Path.Combine(this.ModFullDirectory, entry.FullName.Replace(this.ModDirectory + "/", "")), bytes); // } // catch (Exception e) // { // Console.WriteLine(e); // } // } // } //} return(true); } catch (Exception e) { Console.WriteLine(e); } return(false); }
internal RarArchiveEntry(RarArchive archive, IEnumerable<RarFilePart> parts) { this.parts = parts.ToList(); this.archive = archive; }
Script LoadScript(string p, ScriptType type, Dictionary <string, string> switches = null, Dictionary <string, string[]> assertSwitches = null) { var script = new Script() { name = p.Split('\\').Last() }; string pbase = ""; ZipArchive archive = null; IArchive compress = null; archive = null; MemoryStream zrpstream = null; Bitmap GetBitmap(string path) { if (type == ScriptType.Folder) { if (path == null) { } path = Path.Combine(p, pbase, path); FileStream s; try { s = File.OpenRead(path); } catch { throw new Exception("Could not open " + path); } Bitmap b; try { b = new Bitmap(s); } catch { throw new Exception("Corrupt image: " + path); } s.Close(); return(b); } else if (type == ScriptType.Zip || type == ScriptType.Zrp) { path = Path.Combine(pbase, path); Stream s; try { s = archive.GetEntry(path).Open(); } catch { throw new Exception("Could not open " + path); } Bitmap b; try { b = new Bitmap(s); } catch { throw new Exception("Corrupt image: " + path); } s.Close(); return(b); } else { path = Path.Combine(pbase, path); Stream s; var e = compress.Entries.Where(a => a.Key == path).ToArray(); if (e.Length == 0) { throw new Exception("Could not open " + path); } s = e[0].OpenEntryStream(); Bitmap b; try { b = new Bitmap(s); } catch { throw new Exception("Corrupt image: " + path); } s.Close(); return(b); } } try { string code = ""; if (type == ScriptType.Folder) { var files = Directory.GetFiles(p, "*script.cs", SearchOption.AllDirectories) .Where(s => s.EndsWith("\\script.cs")) .Select(s => s.Substring(p.Length + 1)) .ToArray(); Array.Sort(files.Select(s => s.Length).ToArray(), files); if (files.Length == 0) { throw new Exception("Could not find script.cs file"); } var jsonpath = files[0]; pbase = jsonpath.Substring(0, jsonpath.Length - "script.cs".Length); if (files.Length == 0) { throw new Exception("Could not find script.cs file"); } try { code = File.ReadAllText(Path.Combine(p, jsonpath)); } catch { throw new Exception("Could not read script.cs file"); } } else if (type == ScriptType.Zip || type == ScriptType.Zrp) { if (type == ScriptType.Zrp) { var encoded = File.OpenRead(p); var key = new byte[16]; var iv = new byte[16]; encoded.Read(key, 0, 16); encoded.Read(iv, 0, 16); zrpstream = new MemoryStream(); using (AesManaged aes = new AesManaged()) { ICryptoTransform decryptor = aes.CreateDecryptor(key, iv); using (CryptoStream cs = new CryptoStream(encoded, decryptor, CryptoStreamMode.Read)) { cs.CopyTo(zrpstream); } zrpstream.Position = 0; archive = new ZipArchive(zrpstream); } } else { archive = ZipFile.OpenRead(p); } var files = archive.Entries.Where(e => e.Name == "script.cs").ToArray(); Array.Sort(files.Select(s => s.FullName.Length).ToArray(), files); if (files.Length == 0) { throw new Exception("Could not find script.cs file"); } var jsonfile = files[0]; pbase = jsonfile.FullName.Substring(0, jsonfile.FullName.Length - "script.cs".Length); using (var jfile = new StreamReader(jsonfile.Open())) { code = jfile.ReadToEnd(); } } else { if (type == ScriptType.Rar) { compress = RarArchive.Open(p); } if (type == ScriptType.SevenZip) { compress = SevenZipArchive.Open(p); } if (type == ScriptType.Tar) { compress = TarArchive.Open(p); } var files = compress.Entries.Where(e => e.Key.EndsWith("/script.cs") || e.Key == "script.cs").ToArray(); Array.Sort(files.Select(s => s.Key.Length).ToArray(), files); if (files.Length == 0) { throw new Exception("Could not find script.cs file"); } var jsonfile = files[0]; pbase = jsonfile.Key.Substring(0, jsonfile.Key.Length - "script.cs".Length); using (var jfile = new StreamReader(jsonfile.OpenEntryStream())) { code = jfile.ReadToEnd(); } } var fc = code.Replace(" ", "").Replace("\t", "").Replace("\n", "").Replace("\r", ""); Dictionary <string, string> notallowed = new Dictionary <string, string>() { { "System.IO", null }, { "System.Reflection", null }, { "Microsoft.CSharp", null }, { "System.Net", null }, { "Microsoft.VisualBasic", null }, { "System.Drawing", null }, { "System.AttributeUsage", null }, { "System.EnterpriseServices", null }, { "System.Media", null }, { "System.Messaging", null }, { "System.Printing", null }, { "System.Security", null }, { "System.ServiceModel", null }, { "System.ServiceProcess", null }, { "System.Speech", null }, { "System.Web", null }, { "System.Windows", null }, { "System.Xml", null }, { "Microsoft.Windows", null }, { "Microsoft.Win32", null }, { "Microsoft.SqlServer", null }, { "Microsoft.JScript", null }, { "Microsoft.Build", null }, { "Accessibility", null }, { "Microsoft.Activities", null }, { "System.Diagnostics", "random user" }, { "System.Runtime", "random user" }, { "System.Management", "random user" } }; foreach (var n in notallowed) { if (fc.Contains(n.Key)) { if (n.Value == null) { throw new Exception(n.Key + " is not allowed"); } else if (fc.Contains(n.Key)) { throw new Exception(n.Key + " is not allowed (found by " + n.Value + ")"); } } } CompilerParameters compiler_parameters = new CompilerParameters(); compiler_parameters.GenerateInMemory = true; compiler_parameters.GenerateExecutable = false; compiler_parameters.ReferencedAssemblies.Add(typeof(object).Assembly.Location); compiler_parameters.ReferencedAssemblies.Add(typeof(OpenTK.Vector2).Assembly.Location); compiler_parameters.ReferencedAssemblies.Add(typeof(IEnumerable <object>).Assembly.Location); compiler_parameters.ReferencedAssemblies.Add(typeof(LinkedList <object>).Assembly.Location); compiler_parameters.ReferencedAssemblies.Add(typeof(System.Drawing.Color).Assembly.Location); compiler_parameters.ReferencedAssemblies.Add(typeof(IO).Assembly.Location); compiler_parameters.ReferencedAssemblies.Add(typeof(System.Linq.Enumerable).Assembly.Location); compiler_parameters.CompilerOptions = "/optimize /unsafe /nostdlib"; CompilerResults results = provider.CompileAssemblyFromSource(compiler_parameters, code); if (results.Errors.HasErrors) { StringBuilder builder = new StringBuilder(); foreach (CompilerError error in results.Errors) { builder.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText)); } throw new Exception(String.Format("Error on line {0}:\n{1}", results.Errors[0].Line, results.Errors[0].ErrorText) + "\n" + builder.ToString()); } IO.loadTexture = (path, loop, linear) => { var bmp = GetBitmap(path); var loaded = new Texture() { bitmap = bmp, path = path, width = bmp.Width, height = bmp.Height, aspectRatio = bmp.Width / (double)bmp.Height, looped = loop, linear = linear }; script.textures.Add(loaded); return(loaded); }; IO.loadFont = (size, name, style, chars) => { var font = new Font() { charMap = chars, fontName = name, fontPixelSize = size, fontStyle = style }; script.fonts.Add(font); return(font); }; Assembly assembly = results.CompiledAssembly; var renderType = assembly.GetType("Script"); var instance = (dynamic)Activator.CreateInstance(renderType); script.instance = instance; script.renderType = renderType; IO.callLoadFunction(script.instance); if (renderType.GetField("Description") != null) { script.description = instance.Description; } if (renderType.GetField("Preview") != null) { script.preview = GetBitmap(instance.Preview); } if (renderType.GetMethod("Load") == null) { throw new Exception("Load method required"); } if (renderType.GetMethod("Render") == null) { throw new Exception("Render method required"); } if (renderType.GetMethod("RenderInit") != null) { script.hasPreRender = true; } if (renderType.GetMethod("RenderDispose") != null) { script.hasPostRender = true; } bool hasVar(string name, Type ftype) { if (renderType.GetField(name) != null) { if (ftype.IsAssignableFrom(renderType.GetField(name).FieldType)) { return(true); } } if (renderType.GetProperty(name) != null) { if (ftype.IsAssignableFrom(renderType.GetProperty(name).PropertyType)) { return(true); } } return(false); } if (hasVar("ManualNoteDelete", typeof(bool))) { script.hasManualNoteDelete = true; } if (hasVar("NoteCollectorOffset", typeof(double))) { script.hasCollectorOffset = true; } if (hasVar("NoteScreenTime", typeof(double))) { script.hasNoteScreenTime = true; } if (hasVar("LastNoteCount", typeof(long))) { script.hasNoteCount = true; } if (hasVar("UseProfiles", typeof(bool))) { script.hasProfiles = script.instance.UseProfiles; } if (hasVar("SettingsUI", typeof(IEnumerable <UISetting>))) { script.uiSettings = instance.SettingsUI; } } catch (Exception e) { if (e is TargetInvocationException) { e = e.InnerException; } script.error = true; script.description = e.Message; } finally { if (archive != null) { archive.Dispose(); } if (zrpstream != null) { zrpstream.Dispose(); } if (compress != null) { compress.Dispose(); } } return(script); }
public void decompressRAR(string srcPath, string destPath) { RarArchive.WriteToDirectory(srcPath, destPath); }
public override void Open(string file) { archive = RarArchive.Open (file); Pages = archive.Entries.Where (e => IsValidImage (e.FilePath)).OrderBy (ex => ex.FilePath).Select (f => new RarPage (f)).ToList<Page> (); }
/// <summary> /// Opens a Reader for Non-seeking usage /// </summary> /// <param name="stream"></param> /// <param name="options"></param> /// <returns></returns> public static IReader Open(Stream stream, ReaderOptions options = null) { stream.CheckNotNull("stream"); options = options ?? new ReaderOptions() { LeaveStreamOpen = false }; RewindableStream rewindableStream = new RewindableStream(stream); rewindableStream.StartRecording(); if (ZipArchive.IsZipFile(rewindableStream, options.Password)) { rewindableStream.Rewind(true); return(ZipReader.Open(rewindableStream, options)); } rewindableStream.Rewind(false); if (GZipArchive.IsGZipFile(rewindableStream)) { rewindableStream.Rewind(false); GZipStream testStream = new GZipStream(rewindableStream, CompressionMode.Decompress); if (TarArchive.IsTarFile(testStream)) { rewindableStream.Rewind(true); return(new TarReader(rewindableStream, options, CompressionType.GZip)); } rewindableStream.Rewind(true); return(GZipReader.Open(rewindableStream, options)); } rewindableStream.Rewind(false); if (BZip2Stream.IsBZip2(rewindableStream)) { rewindableStream.Rewind(false); BZip2Stream testStream = new BZip2Stream(rewindableStream, CompressionMode.Decompress, true); if (TarArchive.IsTarFile(testStream)) { rewindableStream.Rewind(true); return(new TarReader(rewindableStream, options, CompressionType.BZip2)); } } rewindableStream.Rewind(false); if (LZipStream.IsLZipFile(rewindableStream)) { rewindableStream.Rewind(false); LZipStream testStream = new LZipStream(rewindableStream, CompressionMode.Decompress, true); if (TarArchive.IsTarFile(testStream)) { rewindableStream.Rewind(true); return(new TarReader(rewindableStream, options, CompressionType.LZip)); } } rewindableStream.Rewind(false); if (RarArchive.IsRarFile(rewindableStream, options)) { rewindableStream.Rewind(true); return(RarReader.Open(rewindableStream, options)); } rewindableStream.Rewind(false); if (TarArchive.IsTarFile(rewindableStream)) { rewindableStream.Rewind(true); return(TarReader.Open(rewindableStream, options)); } rewindableStream.Rewind(false); if (XZStream.IsXZStream(rewindableStream)) { rewindableStream.Rewind(true); XZStream testStream = new XZStream(rewindableStream); if (TarArchive.IsTarFile(testStream)) { rewindableStream.Rewind(true); return(new TarReader(rewindableStream, options, CompressionType.Xz)); } } throw new InvalidOperationException("Cannot determine compressed stream type. Supported Reader Formats: Zip, GZip, BZip2, Tar, Rar, LZip, XZ"); }
// Extract download to Mods directory private async Task ExtractFile(string fileName) { await Task.Run(() => { string _ArchiveSource = $@"{assemblyLocation}/Downloads/{fileName}"; string _ArchiveType = Path.GetExtension(fileName); string ArchiveDestination = $@"{assemblyLocation}/Mods/{response.Name}"; if (File.Exists(_ArchiveSource)) { switch (_ArchiveType) { case ".rar": try { using (var archive = RarArchive.Open(_ArchiveSource)) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { string[] split = entry.ToString().Replace("Entry Path: ", "").Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }); int index = split.ToList().IndexOf("assets"); if (index == 1) { ArchiveDestination = $@"{assemblyLocation}/Mods"; } if (index >= 0 && index < 2) { entry.WriteToDirectory(ArchiveDestination, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } } } catch (Exception e) { MessageBox.Show($"Couldn't extract {fileName}: {e.Message}", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning); } break; case ".zip": try { using (var archive = ZipArchive.Open(_ArchiveSource)) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { string[] split = entry.ToString().Replace("Entry Path: ", "").Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }); int index = split.ToList().IndexOf("assets"); if (index == 1) { ArchiveDestination = $@"{assemblyLocation}/Mods"; } if (index >= 0 && index < 2) { entry.WriteToDirectory(ArchiveDestination, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } } } catch (Exception e) { MessageBox.Show($"Couldn't extract {fileName}: {e.Message}", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning); } break; case ".7z": try { using (var archive = SevenZipArchive.Open(_ArchiveSource)) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { string[] split = entry.ToString().Replace("Entry Path: ", "").Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }); int index = split.ToList().IndexOf("assets"); if (index == 1 && index < 2) { ArchiveDestination = $@"{assemblyLocation}/Mods"; } if (index >= 0) { entry.WriteToDirectory(ArchiveDestination, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } } } catch (Exception e) { MessageBox.Show($"Couldn't extract {fileName}: {e.Message}", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning); } break; default: break; } //File.Delete(_ArchiveSource); // Check if folder output folder exists, if not nothing had an assets folder if (!Directory.Exists(ArchiveDestination)) { MessageBox.Show($"Didn't extract {fileName} due to improper format", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning); } } }); }
internal RarArchiveEntry(int index, RarArchive archive, IEnumerable<RarFilePart> parts) { this.Index = index; this.parts = parts.ToList(); Archive = archive; }
public Func <HttpContent, Task <T> > CreateDeserializer <T>() { if (typeof(T) == typeof(ZipArchive)) { return(async(content) => { var ms = new MemoryStream(); await content.CopyToAsync(ms); var arch = ZipArchive.Open(ms, GetReaderOptions().ReaderOptions); return (T)((object)arch); }); } if (typeof(T) == typeof(RarArchive)) { return(async(content) => { var ms = new MemoryStream(); await content.CopyToAsync(ms); ms.Position = 0; var arch = RarArchive.Open(ms, GetReaderOptions().ReaderOptions); return (T)((object)arch); }); } if (typeof(T) == typeof(GZipArchive)) { return(async(content) => { var ms = new MemoryStream(); await content.CopyToAsync(ms); ms.Position = 0; var arch = GZipArchive.Open(ms, GetReaderOptions().ReaderOptions); return (T)((object)arch); }); } if (typeof(T) == typeof(SevenZipArchive)) { return(async(content) => { var ms = new MemoryStream(); await content.CopyToAsync(ms); ms.Position = 0; var arch = SevenZipArchive.Open(ms, GetReaderOptions().ReaderOptions); return (T)((object)arch); }); } if (typeof(T) == typeof(TarArchive)) { return(async(content) => { if (GetReaderOptions().TarArchivesAreGziped) { var outerms = new MemoryStream(); await content.CopyToAsync(outerms); outerms.Position = 0; var gzarch = GZipArchive.Open(outerms, GetReaderOptions().ReaderOptions); var entry = gzarch.Entries.FirstOrDefault(); using (var readGzStream = entry.OpenEntryStream()) { var innerms = new MemoryStream(); readGzStream.CopyTo(innerms); innerms.Position = 0; var tararch = TarArchive.Open(innerms, GetReaderOptions().ReaderOptions); return (T)((object)tararch); } } else { var ms = new MemoryStream(); await content.CopyToAsync(ms); ms.Position = 0; var arch = TarArchive.Open(ms, GetReaderOptions().ReaderOptions); return (T)((object)arch); } }); } else { throw new NotSupportedException("Type not supported"); } }
public static bool IsRarFile(string rarFileName) { return(RarArchive.IsRarFile(rarFileName)); }
private async Task Extract(String filePath, String destinationFolderPath, String torrentName) { try { if (filePath.EndsWith(".rar")) { ActiveDownload.NewStatus = DownloadStatus.Unpacking; await using (Stream stream = File.OpenRead(filePath)) { using var archive = RarArchive.Open(stream); ActiveDownload.BytesSize = archive.TotalSize; var entries = archive.Entries.Where(entry => !entry.IsDirectory) .ToList(); _rarfileStatus = entries.ToDictionary(entry => entry.Key, entry => 0L); _rarCurrentEntry = null; archive.CompressedBytesRead += ArchiveOnCompressedBytesRead; var extractPath = destinationFolderPath; if (!entries.Any(m => m.Key.StartsWith(torrentName + @"\")) && !entries.Any(m => m.Key.StartsWith(torrentName + @"/"))) { extractPath = Path.Combine(destinationFolderPath, torrentName); } if (entries.Any(m => m.Key.Contains(".r00"))) { extractPath = Path.Combine(extractPath, "Temp"); } foreach (var entry in entries) { _rarCurrentEntry = entry; entry.WriteToDirectory(extractPath, new ExtractionOptions { ExtractFullPath = true, Overwrite = true }); } } var retryCount = 0; while (File.Exists(filePath) && retryCount < 10) { retryCount++; try { File.Delete(filePath); } catch { await Task.Delay(1000); } } } } catch { // ignored } ActiveDownload.Speed = 0; ActiveDownload.BytesDownloaded = ActiveDownload.BytesSize; ActiveDownload.NewStatus = DownloadStatus.Finished; }
/** * <param name="xml_rarEntry"> * RAR entry of the xml file; Will be processed in this class. * </param> * * <param name="comicFile"> * RAR compressed comic file. This class will contain the object to be passed on to other classes. * </param> * * <summary> * Creates a ComicMetadata object using xml rar entry and comicFile rar archive. This class has the * methods to process these parameters into the necessary data. * </summary> */ public ComicMetadata(RarArchiveEntry xml_rarEntry, RarArchive comicFile, StorageFolder tempDir) { this.cbrFile = comicFile; this.tempDir = tempDir; // @TODO : Call the class logic methods to extract metadata. }
private bool Unzip(string PATH_Zip, string PATH_Temp_Mods) // 解压缩 MOD 压缩包文件 { //Debug.Print(DateTime.Now.ToString("mm-ss-ffff")); //Debug.Print(Path.GetExtension(PATH_Zip)); if (Path.GetExtension(PATH_Zip) == ".zip") { using (var archive = ZipArchive.Open(PATH_Zip)) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { entry.WriteToDirectory(PATH_Temp_Mods, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } } else if (Path.GetExtension(PATH_Zip) == ".rar") { using (var archive = RarArchive.Open(PATH_Zip)) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { entry.WriteToDirectory(PATH_Temp_Mods, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } } else if (Path.GetExtension(PATH_Zip) == ".7z") { FileInfo File_Size = new FileInfo(PATH_Zip); Debug.Print(System.Convert.ToInt32(System.Math.Ceiling(File_Size.Length / 1024.0)).ToString()); if (System.Convert.ToInt32(System.Math.Ceiling(File_Size.Length / 1024.0)) > 1024) { if (MessageBox.Show("因软件解压缩库对 7z 格式支持较差,超过 1MB 大小的 .7z 压缩包解压速度会非常慢,造成软件卡死的假象,是否继续载入?" + Line + "强烈推荐大于 1MB 的 .7z 压缩文件自行解压并重新打包为 .zip 压缩格式!", "提示:", MessageBoxButtons.YesNo) == DialogResult.No) { return(false); } } using (var archive = SevenZipArchive.Open(PATH_Zip)) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { entry.WriteToDirectory(PATH_Temp_Mods, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } } else { MessageBox.Show("目前只支持压缩文件格式:.zip(推荐) .rar .7z,其他格式的请手动解压并重新压缩为 .zip 格式(强烈推荐)后重试。", "错误:", MessageBoxButtons.OK); } return(true); //Debug.Print(DateTime.Now.ToString("mm-ss-ffff")); }
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()); } if (rarArchive is null) { return(null); } var needsPassword = false; try { using var testStream = rarArchive.Entries.First().OpenEntryStream(); } catch (Exception) { 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); }
/// <summary> /// RarArchive is part of a multi-part archive. /// </summary> public static bool IsMultipartVolume(/*this*/ RarArchive archive) { return archive.Volumes.First<SharpCompress.Common.Rar.RarVolume>().IsMultiVolume; }