/// <summary> /// 安装补丁 /// </summary> public void Local_patch_POST() { var appDir = Cms.PhysicPath; var filePath = $@"{appDir}{CmsVariables.TEMP_PATH}patch\{Request.Query("file")}"; var file = new FileInfo(filePath); if (file.Exists) { //bool result=ZipUtility.UncompressFile(@"C:\", filePath, true); try { Thread.Sleep(1000); #region dotnetzip /* * * // var options = new ReadOptions { StatusMessageWriter = System.Console.Out }; * using (ZipFile zip = ZipFile.Read(filePath))//, options)) * { * // This call to ExtractAll() assumes: * // - none of the entries are password-protected. * // - want to extract all entries to current working directory * // - none of the files in the zip already exist in the directory; * // if they do, the method will throw. * zip.ExtractAll(appDir,ExtractExistingFileAction.OverwriteSilently); * } * */ #endregion #region sharpcompress var archive = ArchiveFactory.Open(filePath); foreach (var entry in archive.Entries) { if (!entry.IsDirectory) { //Console.WriteLine(entry.FilePath); entry.WriteToDirectory(appDir, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite); } } archive.Dispose(); #endregion } catch (Exception ex1) { Response.WriteAsync(ex1.Message); } } }
/// <summary> /// Initializes a new instance of the <see cref="ArchiveFileLocator"/> class. /// </summary> /// <param name="locator">A file locator.</param> /// <param name="root">The root path.</param> public ArchiveFileLocator(IFileLocator locator, string root) { if (locator != null) { this.fileStream = locator.Open(root); this.archive = ArchiveFactory.Open(this.fileStream); } else { this.archive = ArchiveFactory.Open(root); } }
public void GZip_Archive_Generic() { ResetScratch(); using (Stream stream = File.Open(Path.Combine(TEST_ARCHIVES_PATH, "Tar.tar.gz"), FileMode.Open)) using (var archive = ArchiveFactory.Open(stream)) { var entry = archive.Entries.First(); entry.WriteToFile(Path.Combine(SCRATCH_FILES_PATH, entry.Key)); } CompareArchivesByPath(Path.Combine(SCRATCH_FILES_PATH, "Tar.tar"), Path.Combine(TEST_ARCHIVES_PATH, "Tar.tar")); }
private void UnzipThreadRoutine() { try { if (File.Exists(_downloadSetup.BinsZipLocation)) { Helpers.ConsolePrint(Tag, _downloadSetup.BinsZipLocation + " already downloaded"); Helpers.ConsolePrint(Tag, "unzipping"); // if using other formats as zip are returning 0 var fileArchive = new FileInfo(_downloadSetup.BinsZipLocation); var archive = ArchiveFactory.Open(_downloadSetup.BinsZipLocation); _minerUpdateIndicator.SetMaxProgressValue(100); long sizeCount = 0; foreach (var entry in archive.Entries) { if (!entry.IsDirectory) { sizeCount += entry.CompressedSize; Helpers.ConsolePrint(Tag, entry.Key); entry.WriteToDirectory("", ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite); var prog = sizeCount / (double)fileArchive.Length * 100; _minerUpdateIndicator.SetProgressValueAndMsg((int)prog, string.Format(International.GetText("MinersDownloadManager_Title_Settup_Unzipping"), prog.ToString("F2"))); } } archive.Dispose(); // after unzip stuff _minerUpdateIndicator.FinishMsg(true); // remove bins zip try { if (File.Exists(_downloadSetup.BinsZipLocation)) { File.Delete(_downloadSetup.BinsZipLocation); } } catch (Exception e) { Helpers.ConsolePrint("MinersDownloader.UnzipThreadRoutine", "Cannot delete exception: " + e.Message); } } else { Helpers.ConsolePrint(Tag, $"UnzipThreadRoutine {_downloadSetup.BinsZipLocation} file not found"); } } catch (Exception e) { Helpers.ConsolePrint(Tag, "UnzipThreadRoutine has encountered an error: " + e.Message); } }
/// <summary> /// Распаковывает архив в указанную директорию /// </summary> /// <param name="file">Файл (для получения <c>FileCl.Load()</c>)</param> /// <param name="path">Путь до директории</param> public static void UnpackArchive(this FileCl file, string path, bool overwrite = false) { var archive = ArchiveFactory.Open(file.Path); foreach (var entry in archive.Entries) { entry.WriteToDirectory(path, new ExtractionOptions() { ExtractFullPath = true, Overwrite = overwrite }); } }
/// <summary> /// 解压缩文件 /// </summary> /// <param name="zipedFileName">Zip的完整文件名(如D:\test.zip)</param> /// <param name="targetDirectory">解压到的目录</param> /// <param name="password">解压密码</param> /// <param name="fileFilter">文件过滤正则表达式</param> public static void UnZipFile(string zipedFileName, string targetDirectory, string password, string fileFilter) { using (Stream stream = File.OpenRead(zipedFileName)) using (var archive = ArchiveFactory.Open(stream)) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { entry.WriteToDirectory(targetDirectory, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite); } } }
//mxd private void UpdateArchive(bool enable) { if (enable && archive == null) { archive = ArchiveFactory.Open(location.location); } else if (!enable && !bathmode && archive != null) { archive.Dispose(); archive = null; } }
private void button1_Click(object sender, EventArgs e) { if (Directory.Exists(@"C:/temp")) { Console.Write("Temp directory deleted"); Directory.Delete(@"C:/temp", true); } openFileDialog1.Title = "Open Game..."; openFileDialog1.Filter = "VPK Files |*.vpk|Zip Files |*.zip"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { gameNameLabel.Text = openFileDialog1.FileName; bool isvpk = false; if (openFileDialog1.FileName.Contains(".vpk")) { isvpk = true; File.Move(openFileDialog1.FileName, Path.ChangeExtension(openFileDialog1.FileName, ".zip")); openFileDialog1.FileName = Path.ChangeExtension(openFileDialog1.FileName, ".zip"); } var archive = ArchiveFactory.Open(openFileDialog1.FileName); fileSizeLabel.Text = "File Size: " + archive.TotalSize + " bytes"; statusLabel.Text = "Reading File..."; foreach (var file_ in archive.Entries) { if (file_.Key.Contains("sce_sys") || file_.Key == "eboot.bin") { file_.WriteToDirectory(@"C:\temp\install", ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite); } else { file_.WriteToDirectory(@"C:\temp\data", ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite); } } archive.Dispose(); pictureBox1.ImageLocation = @"C:\temp\install\sce_sys\pic0.png"; statusLabel.Text = "Reading SFO..."; param = new PARAM_SFO(@"C:\temp\install\sce_sys\param.sfo"); gameNameLabel.Text = param.Title; statusLabel.Text = "Game Loaded"; button2.Enabled = true; if (isvpk) { File.Move(openFileDialog1.FileName, Path.ChangeExtension(openFileDialog1.FileName, ".vpk")); } } }
/// <summary> /// 安装补丁 /// </summary> public void Patch_POST() { string appDir = AppDomain.CurrentDomain.BaseDirectory; string filePath = String.Format(@"{0}\patch\{1}", appDir, base.Request["file"]); FileInfo file = new FileInfo(filePath); if (file.Exists) { //bool result=ZipUtility.UncompressFile(@"C:\", filePath, true); try { System.Threading.Thread.Sleep(1000); #region dotnetzip /* * * // var options = new ReadOptions { StatusMessageWriter = System.Console.Out }; * using (ZipFile zip = ZipFile.Read(filePath))//, options)) * { * // This call to ExtractAll() assumes: * // - none of the entries are password-protected. * // - want to extract all entries to current working directory * // - none of the files in the zip already exist in the directory; * // if they do, the method will throw. * zip.ExtractAll(appDir,ExtractExistingFileAction.OverwriteSilently); * } * */ #endregion #region sharpcompress IArchive archive = ArchiveFactory.Open(filePath); foreach (IArchiveEntry entry in archive.Entries) { if (!entry.IsDirectory) { //Console.WriteLine(entry.FilePath); entry.WriteToDirectory(appDir, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite); } } archive.Dispose(); #endregion } catch (System.Exception ex1) { base.Response.Write(ex1.Message); } } }
public SharpCompressArchiver(string archiverPath) : base(archiverPath) { LeaveHistory = true; try { archive = ArchiveFactory.Open(archiverPath); } catch { DisposeArchive(); } }
public static void UnZip(String file, String saveFolder) { var archive = ArchiveFactory.Open(file); foreach (var entry in archive.Entries) { if (!entry.IsDirectory) { Console.WriteLine(entry.FilePath); entry.WriteToDirectory(saveFolder, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite); } } }
public static Tuple <Stream, IDisposable> GetEntryStream(string archivePath, string entryName) { var archive = ArchiveFactory.Open(archivePath); var entry = archive.Entries.FirstOrDefault(a => a.Key == entryName); if (entry == null) { archive.Dispose(); return(null); } return(new Tuple <Stream, IDisposable>(entry.OpenEntryStream(), archive)); }
public void ExtractArchive(string archivePath, string extractTo) { var extOptions = new ExtractionOptions() { ExtractFullPath = false, Overwrite = true }; using (var stream = File.OpenRead(archivePath)) using (var archive = ArchiveFactory.Open(stream)) using (var reader = archive.ExtractAllEntries()) reader.WriteAllToDirectory(extractTo, extOptions); }
/// <summary> /// 解压zip /// </summary> /// <param name="compressfilepath"></param> /// <param name="uncompressdir"></param> private static void UnZip(string compressfilepath, string uncompressdir) { using (var archive = ArchiveFactory.Open(compressfilepath)) { foreach (var entry in archive.Entries) { if (!entry.IsDirectory) { entry.WriteToDirectory(uncompressdir, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite); } } } }
/// <summary> /// 解压文件 /// </summary> /// <param name="targetFile">解压文件路径</param> /// <param name="zipFile">解压文件后路径</param> public static void Decompression(string targetFile, string zipFile) { using (var archive = ArchiveFactory.Open(targetFile)) { foreach (var entry in archive.Entries) { if (!entry.IsDirectory) { entry.WriteToDirectory(zipFile); } } } }
/// <summary> /// 解压文件,自动检测压缩包类型 /// </summary> /// <param name="compressedFile">rar文件</param> /// <param name="dir">解压到...</param> /// <param name="ignoreEmptyDir">忽略空文件夹</param> public void Decompress(string compressedFile, string dir, bool ignoreEmptyDir = true) { if (string.IsNullOrEmpty(dir)) { dir = Path.GetDirectoryName(compressedFile); } ArchiveFactory.WriteToDirectory(compressedFile, Directory.CreateDirectory(dir).FullName, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); }
private IEnumerable <IArchiveEntry> Open(CBookEntity book, List <string> secrets) { string file = Path.Combine(book.Path, book.Name); FileInfo f = new FileInfo(file); if (!f.Exists) { Console.WriteLine("文件不存在..."); return(null); } IArchive archive = null; IEnumerable <IArchiveEntry> entries = null; foreach (var _secret in secrets) { try { if (StringUtils.IsBlank(_secret)) { archive = ArchiveFactory.Open(f); } else { archive = ArchiveFactory.Open(f, new ReaderOptions { Password = _secret }); } entries = archive.Entries; } catch (ArchiveException ex) { Console.WriteLine("压缩包存在问题."); Console.WriteLine(ex); break; } catch (CryptographicException ex) { Console.WriteLine("解压密码不正确."); Console.WriteLine(ex); } } if (entries != null) { } return(entries); }
/// <summary> /// Extracts an archive to a temp cache directory. Returns path to new directory. If temp cache directory already exists, /// will return that without performing an extraction. Returns empty string if there are any invalidations which would /// prevent operations to perform correctly (missing archivePath file, empty archive, etc). /// </summary> /// <param name="archivePath">A valid file to an archive file.</param> /// <param name="extractPath">Path to extract to</param> /// <returns></returns> public void ExtractArchive(string archivePath, string extractPath) { if (!IsValidArchive(archivePath)) { return; } if (Directory.Exists(extractPath)) { return; } var sw = Stopwatch.StartNew(); try { var libraryHandler = CanOpen(archivePath); switch (libraryHandler) { case ArchiveLibrary.Default: { _logger.LogDebug("Using default compression handling"); using var archive = ZipFile.OpenRead(archivePath); ExtractArchiveEntries(archive, extractPath); break; } case ArchiveLibrary.SharpCompress: { _logger.LogDebug("Using SharpCompress compression handling"); using var archive = ArchiveFactory.Open(archivePath); ExtractArchiveEntities(archive.Entries.Where(entry => !entry.IsDirectory && Parser.Parser.IsImage(entry.Key)), extractPath); break; } case ArchiveLibrary.NotSupported: _logger.LogError("[GetNumberOfPagesFromArchive] This archive cannot be read: {ArchivePath}. Defaulting to 0 pages", archivePath); return; default: _logger.LogError("[GetNumberOfPagesFromArchive] There was an exception when reading archive stream: {ArchivePath}. Defaulting to 0 pages", archivePath); return; } } catch (Exception e) { _logger.LogError(e, "There was a problem extracting {ArchivePath} to {ExtractPath}", archivePath, extractPath); return; } _logger.LogDebug("Extracted archive to {ExtractPath} in {ElapsedMilliseconds} milliseconds", extractPath, sw.ElapsedMilliseconds); }
private void startUnzippingClient() { var localFilePath = Path.Combine(installDirectoryText.Text, Client_Folder_Name + ".7z"); unzippingProgressLabel.Text = "--"; var directoryPath = installDirectoryText.Text; new Thread(() => { Thread.CurrentThread.IsBackground = true; var entryCount = 0; Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); using (var archive = ArchiveFactory.Open(localFilePath, new ReaderOptions() { LookForHeader = true })) { var reader = archive.ExtractAllEntries(); while (reader.MoveToNextEntry()) { if (stopwatch.Elapsed.Milliseconds >= 100) { unzippingProgressLabel.Invoke(new Action(() => { unzippingProgressLabel.Text = $"{Math.Round((double)entryCount / archive.Entries.Count() * 100, 2)}% - {entryCount} / {archive.Entries.Count()} files"; })); stopwatch.Restart(); } reader.WriteEntryToDirectory(directoryPath, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true, PreserveAttributes = true, PreserveFileTime = true }); entryCount += 1; } } File.Delete(localFilePath); unzippingProgressLabel.Invoke(new Action(() => { unzippingProgressLabel.Text = "✔️"; startSettingUpTestbox(); })); }).Start(); }
private static void Initialize() { if (_pluginDirName != null) { return; } var assLocation = new DirectoryInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); var directoryName = new DirectoryInfo(Path.Combine(assLocation.FullName, "SB3UGS")); _pluginDirName = new DirectoryInfo(Path.Combine(directoryName.FullName, "plugins")); // bug this can sometimes fail to extract or to load the dlls if (!_pluginDirName.Exists) { if (directoryName.Exists) { directoryName.Delete(true); } Console.WriteLine("Could not find a valid SB3UGS install, attempting to install a fresh one"); var target = assLocation.GetFiles("SB3UGS*.7z").Where(x => !x.Name.Contains("_src")).OrderByDescending(x => x.Length).FirstOrDefault(); if (target != null) { Console.WriteLine("Found " + target.Name + " - attempting to extract"); var extr = ArchiveFactory.Open(target); if (!extr.IsComplete) { throw new IOException("Archive " + target.Name + " is not valid or is corrupted"); } directoryName.Create(); extr.ExtractArchiveToDirectory(directoryName.FullName); _pluginDirName.Refresh(); if (!_pluginDirName.Exists) { throw new IOException("Archive " + target.Name + " did not contain the correct files or it failed to extract"); } } } _sb3uDlls = _pluginDirName.GetFiles("*.dll").Concat(directoryName.GetFiles("*.dll")).ToDictionary(x => Path.GetFileNameWithoutExtension(x.Name), x => x); AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly; LoadPlugin(Path.Combine(_pluginDirName.FullName, "SB3UtilityPlugins.dll")); }
private void bw_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; try { string[] fileEntries; string filePath = pf.pd + @"\" + lastArchName; var archive = ArchiveFactory.Open(filePath); long l = archive.TotalSize; archive.Dispose(); Array.ForEach(Directory.GetFiles(pf.pd + @"\temp"), File.Delete); int i = 0; using (Stream stream = File.OpenRead(filePath)) { var reader = ReaderFactory.Open(stream); while (reader.MoveToNextEntry()) { if ((worker.CancellationPending == true)) { e.Cancel = true; return; } else { var conn = new MySqlConnection("server=" + sCol[0] + ";user="******";database=" + sCol[2] + ";port=" + sCol[3] + ";password="******";"); conn.Open(); var cmd = new MySqlCommand("UPDATE reg19.db_info SET db_info.value = '" + (i++) + "' WHERE paramName = 'procesedXml';", conn); cmd.ExecuteScalar(); reader.WriteEntryToDirectory(pf.pd + @"\temp", ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite); fileEntries = Directory.GetFiles(pf.pd + @"\temp"); xmlsProcess(fileEntries); worker.ReportProgress(i); Array.ForEach(Directory.GetFiles(pf.pd + @"\temp"), File.Delete); } } } var conn1 = new MySqlConnection("server=" + sCol[0] + ";user="******";database=" + sCol[2] + ";port=" + sCol[3] + ";password="******";"); conn1.Open(); var cmd1 = new MySqlCommand("UPDATE db_info SET `value`= '01.05.2016' WHERE paramName = '" + Label2Date.Content + "';", conn1); cmd1.ExecuteScalar(); } catch (Exception ex) { Dispatcher.BeginInvoke(new ThreadStart(delegate { textBox.Text += DateTime.Now.ToString("HH:mm:ss tt") + " Произошла ошибка во время портирования данных: \n"; textBox.Text += ex.Message + "\n"; })); } }
/// <summary> /// Extracts all contents of the given archive file to the destination directory /// </summary> public bool ExtractFiles(string archiveFilePath, string destinationDirectory) { Progress = 0; // Initialize if (!Directory.Exists(destinationDirectory)) { Directory.CreateDirectory(destinationDirectory); } try { // Open reader for all entries using (var archive = ArchiveFactory.Open(archiveFilePath)) { // Closure long archiveSize = new FileInfo(archiveFilePath).Length; // Extract foreach (var entry in archive.Entries) { // Abort check if (AbortChecker()) { return(false); } // Extract file try { var extractOptions = new ExtractionOptions { ExtractFullPath = true, Overwrite = true }; entry.WriteToDirectory(destinationDirectory, extractOptions); Progress += 100.0 * entry.CompressedSize / archiveSize; } catch (Exception ex) { Logger.Record($"Could not unpack an entry from an archive ({entry})"); Logger.Record(ex); } } return(true); } } // Archive is invalid catch (InvalidOperationException ex) { return(false); } }
private string GetXmlStringFromTarXVA() { using (Stream stream = new FileStream(textBoxFile.Text, FileMode.Open, FileAccess.Read)) { ArchiveIterator iterator = ArchiveFactory.Reader(ArchiveFactory.Type.Tar, stream); if (iterator.HasNext()) { Stream ofs = new MemoryStream(); iterator.ExtractCurrentFile(ofs); ofs.Position = 0; return(new StreamReader(ofs).ReadToEnd()); } return(String.Empty); } }
/// <summary> /// ファイル一覧に使用するための子要素を取得します。 /// </summary> /// <returns></returns> public static (IArchive Archive, IEnumerable <ArchiveItem> Children) GetChildrenForList(Stream source) { var opts = new ReaderOptions(); var encoding = Encoding.GetEncoding(932); opts.ArchiveEncoding = new ArchiveEncoding { CustomDecoder = (data, x, y) => encoding.GetString(data) }; var archive = ArchiveFactory.Open(source, opts); return(archive, GetArchiveItemList(archive.Entries)); }
private static IArchive GetArchive(string archive) { lock (Lock) { if (!Archives.TryGetValue(archive, out var arch)) { var fs = new FileStream(archive, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); arch = ArchiveFactory.Open(fs); Archives.Add(archive, arch); } return(arch); } }
public IArchive Archive() { using (Stream hakchiHmod = HmodStream) { MemoryStream tar = new MemoryStream(); using (var extractor = ArchiveFactory.Open(hakchiHmod)) using (var entryStream = extractor.Entries.First().OpenEntryStream()) { entryStream.CopyTo(tar); tar.Position = 0; return(SharpCompress.Archives.Tar.TarArchive.Open(tar)); } } }
private void OpenArchive(string Password = null) { using (var stream = File.OpenRead(this.FilePath)) using (var reader = ArchiveFactory.Open(stream, new ReaderOptions { Password = Password })) { foreach (var item in reader.Entries) { item.WriteToFile(item.Key); break; } } }
void ExtractArchive(string target, string targetDir) { using (var archive = ArchiveFactory.Open(target)) { long done = 0; var totalSize = archive.Entries.Count() + 1; archive.EntryExtractionEnd += (sender, args) => { done++; IndividualProgress = 90 + (10 * done / totalSize); }; archive.WriteToDirectory(targetDir, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite); } }
public void Zip_Removal_Poly() { string scratchPath = Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.noEmptyDirs.zip"); using (ZipArchive vfs = (ZipArchive)ArchiveFactory.Open(scratchPath)) { var e = vfs.Entries.First(v => v.Key.EndsWith("jpg")); vfs.RemoveEntry(e); Assert.Null(vfs.Entries.FirstOrDefault(v => v.Key.EndsWith("jpg"))); Assert.Null(((IArchive)vfs).Entries.FirstOrDefault(v => v.Key.EndsWith("jpg"))); } }
public void Rar_test_invalid_exttime_ArchiveStreamRead() { ResetScratch(); using (var stream = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "test_invalid_exttime.rar"))) { using (var archive = ArchiveFactory.Open(stream)) { foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory)) { entry.WriteToDirectory(SCRATCH_FILES_PATH, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite); } } } }
// public ZipArchive( ArchiveFactory factory, string fileName, ZipFile zipFile ) : base(factory, fileName) { this.zipFile = zipFile; }