/// <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 static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "SevenZip/{account}/{container}/{directory}/{filename}")] HttpRequest req, string account, string container, string directory, string filename, ILogger log) { //Retrieve File from storage var lakeClient = GetDataLakeServiceClient(HttpUtility.UrlDecode(account)); var fileSystemClient = lakeClient.GetFileSystemClient(HttpUtility.UrlDecode(container)); DataLakeDirectoryClient directoryClient = fileSystemClient.GetDirectoryClient(HttpUtility.UrlDecode(directory)); var DownloadFile = directoryClient.GetFileClient(HttpUtility.UrlDecode(filename)); var ReadStream = await DownloadFile.OpenReadAsync(); var response = req.HttpContext.Response; response.StatusCode = 200; response.ContentType = "application/json-data-stream"; using (var archive = SevenZipArchive.Open(ReadStream, null)) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { foreach (IArchiveEntry e in archive.Entries) { e.WriteTo(response.Body); } } } return(new EmptyResult()); }
public async Task ExtractPackageAsync(byte[] file, string destDirPath, IProgress <double> progress = null, CancellationToken cancellationToken = new CancellationToken()) { long totalSize = file.Length; using (Stream memoryStream = new MemoryStream(file)) { if (SevenZipArchive.IsSevenZipFile(memoryStream)) { // 7z is not a streamable format, thus doesn't function with the ReaderFactory API memoryStream.Position = 0; using (var sevenZipArchive = SevenZipArchive.Open(memoryStream)) { var reader = sevenZipArchive.ExtractAllEntries(); await ExtractFromReaderAsync(reader, destDirPath, totalSize, progress); } } else { memoryStream.Position = 0; using (var factory = ReaderFactory.Open(memoryStream)) { await ExtractFromReaderAsync(factory, destDirPath, totalSize, progress); } } } }
/// <summary> /// Extracts a 7z archive and returns a list of extracted filenames. /// </summary> /// <param name="filename">The name of the 7z file.</param> /// <returns>The list of file paths to the extracted files.</returns> private static string[] ExtractSevenZipArchive(string filename) { string dir = filename + "-files"; Directory.CreateDirectory(dir); var result = new List <string>(); using (var archive = SevenZipArchive.Open(filename)) { foreach (var entry in archive.Entries) { if (!entry.IsDirectory) { Console.Write("Extracting {0} ...", entry.Key); var singleFile = Path.Combine(dir, entry.Key); using (var fs = File.Create(singleFile)) { entry.WriteTo(fs); } result.Add(singleFile); Console.WriteLine(" done."); } } } return(result.ToArray()); }
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); }
static void ParseArchive(string archive) { try { using (var arch = SevenZipArchive.Open(archive)) { foreach (var ent in arch.Entries) { var replayName = Path.GetFileNameWithoutExtension(ent.Key); using (var file = ent.OpenEntryStream()) { ParseReplayLog(replayName, file); } } } } catch (Exception e) { exceptions.Writer.TryWrite(Tuple.Create(archive, e)); } if (counterProcessed % 100 == 0) { Console.WriteLine("Processed {0} parsed {1}", counterProcessed, counterParsed); } }
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); } }
public IEnumerable <(string fileName, Stream stream, int size)> GetFiles() { foreach (var path in _paths) { var stream = _fileSystem.File.OpenRead(path); var archive = SevenZipArchive.Open(stream); var allArchiveEntries = archive.ExtractAllEntries(); while (allArchiveEntries.MoveToNextEntry()) { if (allArchiveEntries.Entry.IsDirectory) { continue; } var filename = allArchiveEntries.Entry.Key.ToLowerInvariant(); var entryStream = allArchiveEntries.OpenEntryStream(); yield return( filename, entryStream, (int)Math.Min(int.MaxValue, allArchiveEntries.Entry.Size) ); } } }
/// <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 async override Task <DirectoryInfo> Unpack() { if (packageFile == null || !packageFile.Exists) { throw new InvalidOperationException(); } string filePath = packageFile.FullName; string path = Path.GetDirectoryName(filePath); DirectoryInfo dir = new DirectoryInfo(Path.Combine(path, Path.GetFileNameWithoutExtension(filePath))); dir.Create(); await Task.Run(() => { using (Stream stream = File.OpenRead(filePath)) using (var archive = SevenZipArchive.Open(stream)) { var reader = archive.ExtractAllEntries(); while (reader.MoveToNextEntry()) { if (!reader.Entry.IsDirectory) { reader.WriteEntryToDirectory(dir.FullName, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } } }); return(dir); }
public async Task Install() { Console.WriteLine("Getting link to latest ffmpeg"); string link = await GetLinkFromWebPage(); Console.WriteLine("Downloading ffmpeg"); using (MemoryStream stream = await Download(link)) using (SevenZipArchive archive = SevenZipArchive.Open(stream)) { Console.WriteLine("Unpacking ffmpeg"); string[] files = new string[] { "ffmpeg.exe", "ffprobe.exe" }; foreach (string file in files) { SevenZipArchiveEntry f = archive.Entries.First(x => x.Key.Contains(file)); string name = f.Key.Substring(f.Key.LastIndexOf('/') + 1); CheckDirAndCreate(FolderPath); using (Stream entryStream = f.OpenEntryStream()) using (FileStream fileStream = File.OpenWrite(Path.Combine(FolderPath, name))) await entryStream.CopyToAsync(fileStream); } } Console.WriteLine("Update enviroment"); SetEnvironment(); Console.WriteLine("Set fontconfig"); SetFontConfig(); Console.WriteLine("Copying vp9.exe to " + FolderPath); string location = System.Reflection.Assembly.GetEntryAssembly().Location; File.Copy(location, Path.Combine(FolderPath, Path.GetFileName(location))); }
private static void doUpdate(String currentDirectory, String fileName, String downloadURL) { WebClient clientDL = new WebClient(); String file = currentDirectory + "/" + fileName; //file to download to (install directory + file name extracted from html) Console.WriteLine("Downloading..."); clientDL.DownloadFile(downloadURL, file); //extract and overwrite Console.WriteLine("Extracting..."); using (var archive = SevenZipArchive.Open(file)) { foreach (var entry in archive.Entries) { entry.WriteToDirectory(currentDirectory, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } File.Delete(file); Console.WriteLine("Done!"); }
private static void doUpdate(String currentDirectory, String result) { int start = result.IndexOf("https://ci."); int end = result.IndexOf("7z"); result = result.Substring(start, (end - start) + 2); WebClient clientDL = new WebClient(); int s1 = result.IndexOf("rpcs3"); int e1 = result.IndexOf("7z"); String file = currentDirectory + "/" + result.Substring(s1, (e1 - s1) + 2); //file to download to (install directory + file name extracted from html) Console.WriteLine("Downloading..."); clientDL.DownloadFile(result, file); //extract and overwrite Console.WriteLine("Extracting..."); using (var archive = SevenZipArchive.Open(file)) { foreach (var entry in archive.Entries) { entry.WriteToDirectory(currentDirectory, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } System.IO.File.Delete(file); Console.WriteLine("Done!"); }
public static MainViewModel GetMainViewModel(IObservable <LogEvent> logEvents) { var visualizerService = new ExtendedWpfUIVisualizerService(); visualizerService.Register("TextViewer", typeof(TextViewerWindow)); IDictionary <PhoneModel, IDeployer> deployerDict = new Dictionary <PhoneModel, IDeployer> { { PhoneModel.Lumia950Xl, GetDeployer(Path.Combine("Files", "Lumia 950 XL")) }, { PhoneModel.Lumia950, GetDeployer(Path.Combine("Files", "Lumia 950")) }, }; var api = new LowLevelApi(); var deployersItems = deployerDict.Select(pair => new DeployerItem(pair.Key, pair.Value)).ToList(); var importerItems = new List <DriverPackageImporterItem>() { new DriverPackageImporterItem("7z", new DriverPackageImporter <SevenZipArchiveEntry, SevenZipVolume, SevenZipArchive>( s => SevenZipArchive.Open(s), "Files")), new DriverPackageImporterItem("zip", new DriverPackageImporter <ZipArchiveEntry, ZipVolume, ZipArchive>(s => ZipArchive.Open(s), "Files")) }; var mainViewModel = new MainViewModel(logEvents, deployersItems, importerItems, new ViewServices(new WpfOpenFileService(), DialogCoordinator.Instance, visualizerService), async() => new Phone(await api.GetPhoneDisk())); return(mainViewModel); }
internal void Extract(string path, System.Threading.CancellationToken token) { _total = 0; _completed = 0; using var archive = SevenZipArchive.Open(_zipFile); //try //{ // archive.CompressedBytesRead += Archive_CompressedBytesRead; _total = archive.Entries.Sum(m => m.Size); foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { token.ThrowIfCancellationRequested(); entry.WriteToDirectory(path, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); _completed += entry.Size; UnzipProgressChanged?.Invoke(this, new SevenZipUnzipProgressArgs() { Progress = (float)_completed / _total }); //System.Diagnostics.Debug.WriteLine($"{_completed} {_total}"); } // } // catch (Exception) // { // throw; // } // finally // { // archive.CompressedBytesRead -= Archive_CompressedBytesRead; // } }
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); } }
private static SevenZipArchive OpenSevenZipArchive(string password, Stream stream) { if (string.IsNullOrEmpty(password)) { return(SevenZipArchive.Open(stream)); } return(SevenZipArchive.Open(stream, new ReaderOptions { Password = password })); }
private SevenZipArchive?GetSevenZipArchive(FileEntry fileEntry, ExtractorOptions options) { SevenZipArchive?sevenZipArchive = null; try { sevenZipArchive = SevenZipArchive.Open(fileEntry.Content); } catch (Exception e) { Logger.Debug(Extractor.DEBUG_STRING, ArchiveFileType.P7ZIP, fileEntry.FullPath, string.Empty, e.GetType()); } var needsPassword = false; try { needsPassword = sevenZipArchive?.TotalUncompressSize == 0; } 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 { sevenZipArchive = SevenZipArchive.Open(fileEntry.Content, new SharpCompress.Readers.ReaderOptions() { Password = password }); if (sevenZipArchive.TotalUncompressSize > 0) { passwordFound = true; break; } } catch (Exception e) { Logger.Debug(Extractor.DEBUG_STRING, ArchiveFileType.P7ZIP, fileEntry.FullPath, string.Empty, e.GetType()); } } } } return(sevenZipArchive); }
internal static bool CanOpen(string downloadFile) { try { using var archive = SevenZipArchive.Open(downloadFile); return(archive.Entries.Count > 0); } catch (Exception) { return(false); } }
/// <summary> /// Extracts all from7z. /// </summary> /// <param name="source">The source.</param> /// <param name="targetPath">The target path.</param> /// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param> public void ExtractAllFrom7z(Stream source, string targetPath, bool overwriteExistingFiles) { using var archive = SevenZipArchive.Open(source); using var reader = archive.ExtractAllEntries(); var options = new ExtractionOptions { ExtractFullPath = true, Overwrite = overwriteExistingFiles }; reader.WriteAllToDirectory(targetPath, options); }
private void guna2Button4_Click(object sender, EventArgs e) { ziplocation.Text.Replace(@"//", @"/"); unziplocation.Text.Replace(@"//", @"/"); if (ziplocation.Text.EndsWith(".zip")) { using (var archive = ZipArchive.Open(ziplocation.Text.ToString())) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { entry.WriteToDirectory(unziplocation.Text.ToString(), new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } MessageBox.Show("Extracted!"); } if (ziplocation.Text.EndsWith(".7z")) { using (var archive = SevenZipArchive.Open(ziplocation.Text.ToString())) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { entry.WriteToDirectory(unziplocation.Text.ToString(), new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } MessageBox.Show("Extracted!"); } if (ziplocation.Text.EndsWith(".rar")) { using (var archive = RarArchive.Open(ziplocation.Text.ToString())) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { entry.WriteToDirectory(unziplocation.Text.ToString(), new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } MessageBox.Show("Extracted!"); } }
/// <summary> /// Read archive from a byte[]. The caller must close the returned file provider. /// </summary> /// <param name="data"></param> /// <param name="packageInfo">(optional) clues about the file that is being opened</param> /// <returns>file provider to the contents of the package</returns> public IFileProvider UseBytes(byte[] data, IPackageLoadInfo packageInfo = null) { try { Func <SevenZipArchive> opener = () => SevenZipArchive.Open(new MemoryStream(data)); return(new _7zFileProvider(opener, packageInfo?.Path, packageInfo?.LastModified)); } catch (Exception e) when(e is InvalidDataException || e is FormatException || e is BadImageFormatException) { throw new PackageException.LoadError(null, e); } }
public long GetTotalFileSize() { var sum = 0L; foreach (var path in _paths) { using var archive = SevenZipArchive.Open(path); sum += archive.TotalUncompressSize; } return(sum); }
/// <summary> /// Constructor with IEnumerable FileInfo objects, multi and split support. /// </summary> /// <param name="fileInfos"></param> /// <param name="options"></param> public static IArchive Open(IEnumerable <FileInfo> fileInfos, ReaderOptions options = null) { fileInfos.CheckNotNull(nameof(fileInfos)); FileInfo[] files = fileInfos.ToArray(); if (files.Length == 0) { throw new InvalidOperationException("No files to open"); } FileInfo fileInfo = files[0]; if (files.Length == 1) { return(Open(fileInfo, options)); } fileInfo.CheckNotNull(nameof(fileInfo)); if (options == null) { options = new ReaderOptions { LeaveStreamOpen = false } } ; ArchiveType?type; using (Stream stream = fileInfo.OpenRead()) IsArchive(stream, out type); //test and reset stream position if (type != null) { switch (type.Value) { case ArchiveType.Zip: return(ZipArchive.Open(files, options)); case ArchiveType.SevenZip: return(SevenZipArchive.Open(files, options)); case ArchiveType.GZip: return(GZipArchive.Open(files, options)); case ArchiveType.Rar: return(RarArchive.Open(files, options)); case ArchiveType.Tar: return(TarArchive.Open(files, options)); } } throw new InvalidOperationException("Cannot determine compressed stream type. Supported Archive Formats: Zip, GZip, Tar, Rar, 7Zip"); }
private void DoSevenZip(FileInfo finfo) { using (SevenZipArchive sevenZipArchive = SevenZipArchive.Open(finfo.FullName)) { using (var reader = sevenZipArchive.ExtractAllEntries()) { UpdateList("Opening " + reader.ArchiveType + ": " + finfo.FullName); PeekReader(reader, finfo); } } GC.Collect(); }
public static void ExtraerTodo7ZIP(string Archivo, string CarpetaDestino) { using (var archive = SevenZipArchive.Open(Archivo)) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { entry.WriteToDirectory(CarpetaDestino, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } }
/// <summary> /// 解压 /// </summary> /// <param name="zipFile">压缩包文件</param> /// <param name="extractPath">解压到目录</param> public static void UnZip(string zipFile, string extractPath) { //注意压缩包是zip还是rar string ext = System.IO.Path.GetExtension(zipFile).ToLower(); switch (ext) { case ".7z": using (var archive = SevenZipArchive.Open(zipFile)) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { entry.WriteToDirectory(extractPath, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } break; case ".zip": using (var archive = ZipArchive.Open(zipFile)) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { entry.WriteToDirectory(extractPath, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } break; case ".rar": default: using (var archive = RarArchive.Open(zipFile)) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { entry.WriteToDirectory(extractPath, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } break; } }
private void unSeven(string target) { using (var archive = SevenZipArchive.Open(target)) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { entry.WriteToDirectory("cache\\unpack", new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } }
private static Stream Add7zLayer(Stream input) { SevenZipArchive zip = SevenZipArchive.Open(input); foreach (SevenZipArchiveEntry entry in zip.Entries) { if (CanDec(entry.Key)) { filein = entry.Key; return(entry.OpenEntryStream()); } } throw new Exception("No compatible file found in the .7z"); }
public void Extract7Z(string rarFileName, string targetDir) { using (var archive = SevenZipArchive.Open(rarFileName)) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { entry.WriteToDirectory(targetDir, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } }