protected override void Install(Stream updateStream) { string tempDir = null; try { using (var extractor = new SevenZip.SevenZipExtractor(updateStream)) { extractor.ExtractArchive(Path.GetTempPath()); tempDir = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(UpdateRelativeUrl)); } IOExt.MoveDirWithOverwrite(tempDir, MEDIA_PLAYER_PATH); } catch (SevenZip.SevenZipException x) { throw new UpdaterException(x.Message, x); } finally { if (tempDir != null && Directory.Exists(tempDir)) { Directory.Delete(tempDir, true); } } }
/// <summary> /// Extracts all dat archives to C:\skeletonKey\SourceDats\ /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void btnDeArchiveDATs_Click(object sender, RoutedEventArgs e) { var dats = DATFile.GetDatFiles(); string outputDir = @"C:\skeletonKey\SourceDats\"; Directory.CreateDirectory(outputDir); Console.WriteLine("Retrieving local DAT file archives - Count: " + dats.Count()); Console.WriteLine("Extracting DATs to " + outputDir); await Task.Run(() => { foreach (var d in dats) { try { using (SevenZip.SevenZipExtractor archive = new SevenZip.SevenZipExtractor(d)) { Console.WriteLine("Extracting: " + Path.GetFileName(d) + " To: " + outputDir + Path.GetFileNameWithoutExtension(d)); archive.ExtractArchive(outputDir); } } catch (Exception ex) { string eS = ex.ToString(); } } }); Console.WriteLine("------------Done------------"); }
public static void convertZipInFileSystem(string zipfile) { FileStream _7zfile = File.Create(Path.GetFileNameWithoutExtension(zipfile) + ".7z"); SevenZip.SevenZipExtractor ze = new SevenZip.SevenZipExtractor(zipfile); string tempdirectory = Path.Combine(Environment.CurrentDirectory, zipfile + "7z"); Directory.CreateDirectory(tempdirectory); ze.ExtractArchive(tempdirectory); ze.Dispose(); SevenZip.SevenZipCompressor _7zc = new SevenZip.SevenZipCompressor(); Dictionary <string, string> newentry = new Dictionary <string, string>(); _7zc.ArchiveFormat = SevenZip.OutArchiveFormat.SevenZip; _7zc.CompressionLevel = SevenZip.CompressionLevel.High; _7zc.CompressionMode = SevenZip.CompressionMode.Create; _7zc.DirectoryStructure = true; _7zc.FastCompression = true; Console.WriteLine("Beginning compression. This will take a while..."); _7zc.CompressDirectory(tempdirectory, _7zfile); _7zfile.Close(); Directory.Delete(tempdirectory, true); Console.WriteLine("Done."); }
public override void Execute() { SevenZip.SevenZipExtractor.SetLibraryPath(System.IO.Path.Combine(Program.BaseDirectoryInternal, IntPtr.Size == 8 ? @"tools\7z64.dll" : @"tools\7z.dll")); int done = 0; foreach (string f in _filesToDir.Keys) { using (var szExtractor = new SevenZip.SevenZipExtractor(f)) { ReportStatus("Extracting " + f); try { System.IO.Directory.CreateDirectory(_filesToDir[f]); szExtractor.ExtractArchive(_filesToDir[f]); done++; } catch (Exception exc) { ReportError("Cannot extract " + f + "\r\n" + exc.Message, false); } ReportProgress(done * 100 / _filesToDir.Count); } } ReportCompleted(); }
/// <summary> /// Unzip a Zip file to a defined folder /// </summary> /// <param name="zipFilename"></param> /// <param name="outputFolder"></param> /// <returns></returns> public String UnzipFile(String outputFolder) { DirectoryInfo[] startDirectories = (new DirectoryInfo(outputFolder)).GetDirectories(); String t = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + SevenZipFolderLocation; SevenZip.SevenZipBase.SetLibraryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + SevenZipFolderLocation); SevenZip.SevenZipExtractor ex = new SevenZip.SevenZipExtractor(zipFileLocation.FullName); ex.ExtractionFinished += (s, e) => { logger.Info("Extracting finished"); }; ex.ExtractArchive(outputFolder); String parentFile = null; foreach (SevenZip.ArchiveFileInfo zipFile in ex.ArchiveFileData) { if (parentFile == null || parentFile.Length > zipFile.FileName.Length) { parentFile = zipFile.FileName; } } if (parentFile.Contains("\\")) { parentFile = parentFile.Substring(0, parentFile.IndexOf("\\")); } return Path.Combine(outputFolder, parentFile); }
/// <summary> /// Unzip a Zip file to a defined folder /// </summary> /// <param name="zipFilename"></param> /// <param name="outputFolder"></param> /// <returns></returns> public String UnzipFile(String outputFolder) { DirectoryInfo[] startDirectories = (new DirectoryInfo(outputFolder)).GetDirectories(); String t = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + SevenZipFolderLocation; SevenZip.SevenZipBase.SetLibraryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + SevenZipFolderLocation); SevenZip.SevenZipExtractor ex = new SevenZip.SevenZipExtractor(zipFileLocation.FullName); ex.ExtractionFinished += (s, e) => { logger.Info("Extracting finished"); }; ex.ExtractArchive(outputFolder); String parentFile = null; foreach (SevenZip.ArchiveFileInfo zipFile in ex.ArchiveFileData) { if (parentFile == null || parentFile.Length > zipFile.FileName.Length) { parentFile = zipFile.FileName; } } if (parentFile.Contains("\\")) { parentFile = parentFile.Substring(0, parentFile.IndexOf("\\")); } return(Path.Combine(outputFolder, parentFile)); }
private Boolean UnpackNewVersion() { if (Path.GetExtension(m_LatestVersionArchivePath) == ".rar") { try { SevenZip.SevenZipExtractor.SetLibraryPath(m_7zLibraryPath); SevenZip.SevenZipExtractor extract = new SevenZip.SevenZipExtractor(m_LatestVersionArchivePath); extract.ExtractArchive(m_TemporaryNewVersionFolder); File.Delete(m_LatestVersionArchivePath); return(true); } catch { return(false); } } //Handle WiX installers for automatic install users. else { try { Process.Start(m_LatestVersionArchivePath).WaitForExit(); return(true); } catch { return(false); } } }
//This event handler processes the extraction of the package private void InstallerWorker_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; string extractiondirectory = StartWindowForm.OpenBVELocation + currentpackage.installpath; var installpackage = new SevenZip.SevenZipExtractor(openfile); installpackage.ExtractArchive(Path.Combine(StartWindowForm.OpenBVELocation + "\\" + currentpackage.installpath)); StartWindowForm.installedpackages.Add(currentpackage.guid, currentpackage); //Move the package image to the database if we created one if (File.Exists(Path.Combine(StartWindowForm.OpenBVELocation + "\\package.png"))) { File.Move(Path.Combine(StartWindowForm.OpenBVELocation + "\\package.png"), Path.Combine(StartWindowForm.imagefolder + "\\" + currentpackage.guid + ".png")); } //Delete the package info file we extracted if (File.Exists(Path.Combine(StartWindowForm.OpenBVELocation + "\\packageinfo.bpi"))) { File.Delete(Path.Combine(StartWindowForm.OpenBVELocation + "\\packageinfo.bpi")); } //If we have a package image set for an archive, copy it rather than moving it if (File.Exists(packageimage)) { File.Copy(packageimage, Path.Combine(StartWindowForm.imagefolder + "\\" + currentpackage.guid + ".png")); } updatedatabase(); }
public void Load(string _pathlog, string _pathscript, string transid) { this.pathScript = _pathscript; if (transid.ToLower().IndexOf("0x") == 0) { transid = transid.Substring(2); } byte[] info = HexString2Bytes(transid); var filename = "0x" + ToHexString(info); var tranfile = System.IO.Path.Combine(_pathlog, filename + ".fulllog.7z"); if (System.IO.File.Exists(tranfile) == false) { throw new Exception("你的数据源里没有log信息,他可能还没有同步,或者这不是一个智能合约交易"); } using (var ms = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(tranfile))) { SevenZip.SevenZipExtractor e7z = new SevenZip.SevenZipExtractor(ms); var outms = new System.IO.MemoryStream(); e7z.ExtractFile(0, outms); var text = System.Text.Encoding.UTF8.GetString(outms.ToArray()); var json = MyJson.Parse(text) as MyJson.JsonNode_Object; fullLog = SmartContract.Debug.FullLog.FromJson(json); } //循环所有的 simvm.Execute(fullLog); }
public void Dispose() { if (_extractor != null) { _extractor.Dispose(); _extractor = null; } }
private void upZipCodecs() { if (Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\codecs") == false) { string codecsZip = AppDomain.CurrentDomain.BaseDirectory + "\\codecs.zip"; SevenZip.SevenZipExtractor sze = new SevenZip.SevenZipExtractor(codecsZip); sze.ExtractArchive(AppDomain.CurrentDomain.BaseDirectory + "\\codecs"); } }
private void menuItem1_Click(object sender, System.EventArgs e) { var fileName = Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\gpl.7z"; tb_Log.Text += "File name is \"" + fileName + "\"" + Environment.NewLine; using (var extr = new SevenZip.SevenZipExtractor(fileName)) { tb_Log.Text += "The archive was successfully identified. Ready to extract" + Environment.NewLine; extr.ExtractArchive(Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)); tb_Log.Text += "Extracted successfully!" + Environment.NewLine; } tb_Log.Text += "Performing an internal benchmark..." + Environment.NewLine; var features = SevenZip.SevenZipExtractor.CurrentLibraryFeatures; tb_Log.Text += "Finished. The score is " + ((uint)features).ToString("X6") + Environment.NewLine; }
protected override bool Do() { SevenZip.SevenZipExtractor extr; if (ArchPass.Length > 0) { extr = new SevenZip.SevenZipExtractor(ArchPath, ArchPass); } else { extr = new SevenZip.SevenZipExtractor(ArchPath); } extr.Extracting += (pdn, pdt) => Action("Распаковка", 100, pdt.PercentDone); extr.ExtractArchive(StartupPath); extr.Dispose(); return(true); }
//Event handler for selected tabs private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) { string temppath = GetTemporaryDirectory(); SevenZip.SevenZipExtractor.SetLibraryPath(@"D:\Program Files (x86)\7-Zip\7z.dll"); switch ((sender as TabControl).SelectedIndex) { case 0: //Starting tab, twiddle break; case 1: //We've selected the second tab and need to load the package information from the archive if (File.Exists(openfile)) { string tempextract_info = Path.Combine(temppath + "\\packageinfo.bpi"); try { using (FileStream myStream = new FileStream(tempextract_info, FileMode.Create)) { var packageinfofile = new SevenZip.SevenZipExtractor(openfile); packageinfofile.ExtractFile("packageinfo.bpi", myStream); } } catch { MessageBox.Show("The selected package appears to be corrupt."); } try { readpackageinfo(tempextract_info); } catch { MessageBox.Show("Error reading package information."); } //Now extract the image try { string tempextract_image = Path.Combine(temppath + "\\package.png"); using (FileStream myStream = new FileStream(tempextract_image, FileMode.Create)) { var packageimage = new SevenZip.SevenZipExtractor(openfile); packageimage.ExtractFile("package.png", myStream); } //Read the package information readpackageinfo(tempextract_info); //Load the image Bitmap tempimage; using (FileStream myStream = new FileStream(tempextract_image, FileMode.Open)) { tempimage = (Bitmap)Image.FromStream(myStream); this.pictureBox1.Image = tempimage; this.pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; } } catch { //No error prompt, just don't load the image } } break; case 2: //Try to load the contents of an archive if (ArchiveInfoWorker.IsBusy != true) { progress1 = new ReadingPackage(); progress1.Show(); ArchiveInfoWorker.RunWorkerAsync(); } break; case 3: //Package extraction if (InstallerWorker.IsBusy != true) { progress = new InstallProgress(); progress.Show(); InstallerWorker.RunWorkerAsync(); } break; } }
async void DownloadUpdateButton_Click(object sender, EventArgs e) { DownloadUpdateButton.Enabled = false; CheckServerButton.Enabled = false; FlashUpdateButton.Enabled = false; FirmwareUpdateCheckingLoadingPictureBox.Visible = false; StatusLabel.Text = "Retrieving server filename extension for download..."; StatusLabel.ForeColor = Color.DarkGreen; if (!Directory.Exists(string.Format(@"{0}\IME Firmware Update", Environment.GetFolderPath(Environment.SpecialFolder.Desktop)))) Directory.CreateDirectory(string.Format(@"{0}\IME Firmware Update", Environment.GetFolderPath(Environment.SpecialFolder.Desktop))); if (!Directory.Exists(string.Format(@"{0}\IME Firmware Update\{1}", Environment.GetFolderPath(Environment.SpecialFolder.Desktop), ServerVersion))) Directory.CreateDirectory(string.Format(@"{0}\IME Firmware Update\{1}", Environment.GetFolderPath(Environment.SpecialFolder.Desktop), ServerVersion)); try { if (File.Exists(string.Format(@"{0}\IME Firmware Update\{1}\Update{2}", Environment.GetFolderPath(Environment.SpecialFolder.Desktop), ServerVersion, ServerFileExtension))) File.Delete(string.Format(@"{0}\IME Firmware Update\{1}\Update{2}", Environment.GetFolderPath(Environment.SpecialFolder.Desktop), ServerVersion, ServerFileExtension)); } catch { } await Task.Run(async delegate { using (var Client = new WebClient()) { Client.OpenRead(UpdateDownloadLink); string Header_ContentDisposition = Client.ResponseHeaders["content-disposition"]; try { ServerFileExtension = Path.GetExtension(new ContentDisposition(Header_ContentDisposition).FileName); } catch { ServerFileExtension = Path.GetExtension(UpdateDownloadLink.AbsoluteUri); } #region Progress Changed Client.DownloadProgressChanged += async delegate(object DownloadProgressSender, DownloadProgressChangedEventArgs Event) { try { int Percent = Convert.ToInt32(Math.Truncate((Convert.ToDouble(Event.BytesReceived / 100) / Convert.ToDouble(Event.TotalBytesToReceive / 100)) * 100)); Invoke(new Action(delegate { if (StatusLabel.ForeColor != Color.DarkGreen) StatusLabel.ForeColor = Color.DarkGreen; StatusLabel.Text = string.Format("Downloading update {0}%...", Percent); })); } catch { } }; #endregion #region Download Complete Client.DownloadFileCompleted += async delegate(object DownloadFileSender, AsyncCompletedEventArgs Event) { Invoke(new Action(delegate { try { if (Event.Error == null) { StatusLabel.Text = "Download Complete! ✔"; StatusLabel.ForeColor = Color.DarkGreen; if (ServerFileExtension != ".zip") { StatusLabel.Text = string.Format("Extracting {0}...", ServerFileExtension); if (Environment.Is64BitProcess) SevenZip.SevenZipExtractor.SetLibraryPath(string.Format(@"{0}\{1}.dll", Application.StartupPath, "7z64")); else SevenZip.SevenZipExtractor.SetLibraryPath(string.Format(@"{0}\{1}.dll", Application.StartupPath, "7z")); SevenZip.SevenZipExtractor TempFile = new SevenZip.SevenZipExtractor(string.Format(@"{0}\IME Firmware Update\{1}\Update{2}", Environment.GetFolderPath(Environment.SpecialFolder.Desktop), ServerVersion, ServerFileExtension)); TempFile.BeginExtractArchive(Path.GetDirectoryName(string.Format(@"{0}\IME Firmware Update\{1}\", Environment.GetFolderPath(Environment.SpecialFolder.Desktop), ServerVersion))); TempFile.ExtractionFinished += TempFile_ExtractionFinished; return; } else { StatusLabel.Text = "Extracting .zip..."; ZipFile.ExtractToDirectory(string.Format(@"{0}\IME Firmware Update\{1}\Update{2}", Environment.GetFolderPath(Environment.SpecialFolder.Desktop), ServerVersion, ServerFileExtension), string.Format(@"{0}\IME Firmware Update\{1}", Environment.GetFolderPath(Environment.SpecialFolder.Desktop), ServerVersion)); StatusLabel.Text = "Extracting .zip Complete! ✔"; FlashUpdateButton.Enabled = true; CheckServerButton.Enabled = true; DownloadUpdateButton.Enabled = true; } } else { try { if (File.Exists(string.Format(@"{0}\IME Firmware Update\{1}\Update{2}", Environment.GetFolderPath(Environment.SpecialFolder.Desktop), ServerVersion, ServerFileExtension))) File.Delete(string.Format(@"{0}\IME Firmware Update\{1}\Update{2}", Environment.GetFolderPath(Environment.SpecialFolder.Desktop), ServerVersion, ServerFileExtension)); } catch { } CheckServerButton.Enabled = true; DownloadUpdateButton.Enabled = true; FlashUpdateButton.Enabled = false; MessageBox.Show(this, Event.Error.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { try { if (File.Exists(string.Format(@"{0}\IME Firmware Update\{1}\Update{2}", Environment.GetFolderPath(Environment.SpecialFolder.Desktop), ServerVersion, ServerFileExtension))) File.Delete(string.Format(@"{0}\IME Firmware Update\{1}\Update{2}", Environment.GetFolderPath(Environment.SpecialFolder.Desktop), ServerVersion, ServerFileExtension)); } catch { } CheckServerButton.Enabled = true; DownloadUpdateButton.Enabled = true; FlashUpdateButton.Enabled = false; MessageBox.Show(this, ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } })); Application.ExitThread(); }; #endregion await Client.DownloadFileTaskAsync(UpdateDownloadLink, string.Format(@"{0}\IME Firmware Update\{1}\Update{2}", Environment.GetFolderPath(Environment.SpecialFolder.Desktop), ServerVersion, ServerFileExtension)); } }); }
public void OpenRom(string fileName) { // Pause emulation if (NesEmu.EmulationON) NesEmu.EmulationPaused = true; switch (Path.GetExtension(fileName).ToLower()) { case ".7z": case ".zip": case ".rar": case ".gzip": case ".tar": case ".bzip2": case ".xz": { string tempFolder = Path.GetTempPath() + "\\MYNES\\"; SevenZip.SevenZipExtractor EXTRACTOR; try { EXTRACTOR = new SevenZip.SevenZipExtractor(fileName); } catch (Exception ex) { ManagedMessageBox.ShowErrorMessage(ex.Message); return; } if (EXTRACTOR.ArchiveFileData.Count == 1) { if (EXTRACTOR.ArchiveFileData[0].FileName.Substring(EXTRACTOR.ArchiveFileData[0].FileName.Length - 4, 4).ToLower() == ".nes") { EXTRACTOR.ExtractArchive(tempFolder); fileName = tempFolder + EXTRACTOR.ArchiveFileData[0].FileName; } } else { List<string> filenames = new List<string>(); foreach (SevenZip.ArchiveFileInfo file in EXTRACTOR.ArchiveFileData) { filenames.Add(file.FileName); } FormFilesList ar = new FormFilesList(filenames.ToArray()); if (ar.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) { string[] fil = { ar.SelectedRom }; EXTRACTOR.ExtractFiles(tempFolder, fil); fileName = tempFolder + ar.SelectedRom; } else { return; } } } break; } try { NesEmu.EmulationPaused = true;// Make sure it's still paused ! bool is_supported_mapper; bool has_issues; string issues; if (NesEmu.CheckRom(fileName, out is_supported_mapper, out has_issues, out issues)) { if (!is_supported_mapper && !Program.Settings.IgnoreNotSupportedMapper) { ManagedMessageBoxResult res = ManagedMessageBox.ShowQuestionMessage( Program.ResourceManager.GetString("Message_ThisGameMapperMarkedAsNotSupported"), "My Nes", null, true, Program.Settings.IgnoreNotSupportedMapper, Program.ResourceManager.GetString("Text_AlwaysTryToRunGameWithNoSupportedMappers")); Program.Settings.IgnoreNotSupportedMapper = res.Checked; if (res.ClickedButtonIndex == 1)// No return; } if (has_issues && Program.Settings.ShowRomIssuesIfHave) { ManagedMessageBoxResult res = ManagedMessageBox.ShowMessage( Program.ResourceManager.GetString("Message_ThisGameHaveKnownIssues") + ":\n" + issues, "My Nes", null, true, Program.Settings.ShowRomIssuesIfHave, Program.ResourceManager.GetString("Text_AlwaysWarnAboutIssues")); Program.Settings.ShowRomIssuesIfHave = res.Checked; } NesEmu.EmulationON = false; // Kill the original thread if (NesEmu.EmulationThread != null) // while (NesEmu.EmulationThread.IsAlive) // { } if (NesEmu.EmulationThread.IsAlive) NesEmu.EmulationThread.Abort(); // Shutdown emu NesEmu.ShutDown(); // Settings first ApplyEmuSettings(); // Create new NesEmu.CreateNew(fileName, Program.Settings.TVSystemSetting, true); // Stop video for a while video.threadPAUSED = true; // Apply video stretch ApplyVideoStretch(); // Reset video renderer video.Reset(); InitializeInputRenderer(); if (NesEmu.IsGameFoundOnDB) { if (NesEmu.GameInfo.Game_AltName != null && NesEmu.GameInfo.Game_AltName != "") this.Text = NesEmu.GameInfo.Game_Name + " (" + NesEmu.GameInfo.Game_AltName + ") - My Nes"; else this.Text = NesEmu.GameInfo.Game_Name + " - My Nes"; } else { this.Text = Path.GetFileName(NesEmu.GAMEFILE) + " - My Nes"; } NesEmu.EmulationPaused = false; } else { ManagedMessageBox.ShowErrorMessage("My Nes can't run this game.", "My Nes"); if (NesEmu.EmulationON) NesEmu.EmulationPaused = false; } } catch (Exception ex) { ManagedMessageBox.ShowErrorMessage(ex.Message, "My Nes"); if (NesEmu.EmulationON) NesEmu.EmulationPaused = false; } }
private void Open(string path) { _extractor = new SevenZip.SevenZipExtractor(path); }
public Unzipper(string zipfile) { _zipfile = zipfile; fz = new SevenZip.SevenZipExtractor(zipfile); }
private void btnSendDebug_Click(object sender, EventArgs e) { string szdll = ""; if (Environment.Is64BitProcess) { szdll = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "7z.dll"); } else { szdll = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "7z32.dll"); } if (btnSendDebug.Text != "Fetch data") //If not in receive mode { string password = Guid.NewGuid().ToString().Replace("-", "").Replace("{", "").Replace("}", "").ToUpper(); string relativedir = Directory.GetCurrentDirectory(); string tempdebugdir = Path.Combine(relativedir, "debug"); string tempzipfile = tempdebugdir + ".7z"; if (!Directory.Exists(tempdebugdir)) { Directory.CreateDirectory(tempdebugdir); } string[] debugFiles = Directory.GetFiles(tempdebugdir); foreach (string file in debugFiles) { File.Delete(file); } if (File.Exists(tempzipfile)) { File.Delete(tempzipfile); } //Exporting side string sideFile = Path.Combine(tempdebugdir, "SIDE.txt"); File.WriteAllText(sideFile, System.Diagnostics.Process.GetCurrentProcess().ProcessName); //Exporting Stacktrace var _ex = ex; StringBuilder sb = new StringBuilder(); sb.AppendLine($"Exception: {ex.Message}\n{ex.StackTrace}"); while (_ex.InnerException != null) { sb.AppendLine(); sb.AppendLine($"Inner Exception: {ex.Message}\n{ex.StackTrace}"); _ex = _ex.InnerException; } tbStackTrace.Text = sb.ToString(); string stacktracefile = Path.Combine(tempdebugdir, "STACKTRACE.TXT"); File.WriteAllText(stacktracefile, sb.ToString()); //Exporting data string data = Path.Combine(tempdebugdir, "DATA.TXT"); sb = new StringBuilder(); foreach (var key in ex.Data.Keys) { sb.AppendLine(key + " : " + ex.Data[key]); } File.WriteAllText(data, sb.ToString()); //Exporting Specs from RTC's perspective string rtcfile = Path.Combine(tempdebugdir, "RTC_PERSPECTIVE.TXT"); File.WriteAllText(rtcfile, getRTCInfo()); //Exporting Specs from the Emu's perspective string emufile = Path.Combine(tempdebugdir, "EMU_PERSPECTIVE.txt"); File.WriteAllText(emufile, getEmuInfo()); //Copying the log files if (AllSpec.CorruptCoreSpec?["RTCDIR"] is string rtcdir) { string rtcLog = Path.Combine(rtcdir, "RTC_LOG.txt"); string rtcLogOutput = Path.Combine(tempdebugdir, "RTC_LOG.txt"); //lock (NetCore_Extensions.ConsoleHelper.con.FileWriter) //{ if (File.Exists(rtcLog)) { File.Copy(rtcLog, rtcLogOutput, true); } //} } if (AllSpec.VanguardSpec?["EMUDIR"] is string emudir) { string emuLog = Path.Combine(emudir, "EMU_LOG.txt"); string emuLogOutput = Path.Combine(tempdebugdir, "EMU_LOG.txt"); //lock (NetCore_Extensions.ConsoleHelper.con.FileWriter) //{ if (File.Exists(emuLog)) { File.Copy(emuLog, emuLogOutput, true); } //} } SevenZip.SevenZipBase.SetLibraryPath(szdll); var comp = new SevenZip.SevenZipCompressor { CompressionMode = SevenZip.CompressionMode.Create, TempFolderPath = Path.GetTempPath(), ArchiveFormat = SevenZip.OutArchiveFormat.SevenZip }; comp.CompressDirectory(tempdebugdir, tempzipfile, false, password); string filename = CloudTransfer.CloudSave(tempzipfile); tbKey.Text = filename + "-" + password; btnSendDebug.Enabled = false; if (File.Exists(tempzipfile)) { File.Delete(tempzipfile); } } else { if (tbKey.Text.Length != 65) { MessageBox.Show("Invalid key"); return; } string[] keyparts = tbKey.Text.Split('-'); string filename = keyparts[0]; string password = keyparts[1]; string downloadfilepath = CloudTransfer.CloudLoad(filename, password); if (downloadfilepath == null) { return; } string extractpath = downloadfilepath.Replace(".7z", ""); if (!Directory.Exists(extractpath)) { Directory.CreateDirectory(extractpath); } string[] debugFiles = Directory.GetFiles(extractpath); foreach (string file in debugFiles) { File.Delete(file); } SevenZip.SevenZipCompressor.SetLibraryPath(szdll); var decomp = new SevenZip.SevenZipExtractor(downloadfilepath, password, SevenZip.InArchiveFormat.SevenZip); decomp.ExtractArchive(extractpath); File.Delete(downloadfilepath); Process.Start(extractpath); } }
//This event handler processes the archive's contents private void ArchiveInfoWorker_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; var readarchive = new SevenZip.SevenZipExtractor(openfile); //Read the archive's contents into our list archivecontents = readarchive.ArchiveFileNames.ToList <string>(); if (archivecontents.Count > 0) { { foreach (string item in archivecontents) { //Test potential paths // //Complete, easily identifiable packages if (item.StartsWith("railway\\", StringComparison.OrdinalIgnoreCase)) { currentpackage.installpath = ""; this.Invoke((MethodInvoker) delegate { label2.Text = "ROUTE"; }); pathfound = true; break; } else if (item.StartsWith("route\\", StringComparison.OrdinalIgnoreCase) || item.StartsWith("object\\", StringComparison.OrdinalIgnoreCase) || item.StartsWith("sound\\", StringComparison.OrdinalIgnoreCase)) { currentpackage.installpath = "\\Railway"; this.Invoke((MethodInvoker) delegate { label2.Text = "ROUTE COMPONENT (Full path found)"; }); pathfound = true; break; } else if (item.StartsWith("train\\", StringComparison.OrdinalIgnoreCase)) { currentpackage.installpath = ""; this.Invoke((MethodInvoker) delegate { label2.Text = "TRAIN (Full path found)"; }); pathfound = true; break; } else if (item.EndsWith("train.dat", StringComparison.OrdinalIgnoreCase) || item.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) { //We've found a train.dat file or a DLL trainfiles++; } else if (item.EndsWith(".csv", StringComparison.OrdinalIgnoreCase)) { //We've found a CSV file, increment the counter by one csvfiles++; } else if (item.EndsWith(".b3d", StringComparison.OrdinalIgnoreCase)) { //We've found a CSV file, increment the counter by one b3dfiles++; } else if (item.EndsWith(".wav", StringComparison.OrdinalIgnoreCase) || item.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase)) { //We've found a CSV file, increment the counter by one soundfiles++; } else if (item.EndsWith(".png", StringComparison.OrdinalIgnoreCase) || item.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase) || item.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase)) { //We've found an image file, increment the counter by one imagefiles++; } } if (pathfound == false) { //No easily identifiable path was found- Try and figure it out manually from the archive contents. if ((csvfiles < 50 || b3dfiles < 50) && imagefiles < 50) { //We've got more than 50 objects and images //This suggests that this is an *object* archive currentpackage.installpath = "\\Railway\\Object"; this.Invoke((MethodInvoker) delegate { label2.Text = "ROUTE OBJECTS (Full path not found)"; }); } else if (soundfiles < 10 && trainfiles == 0) { //We've got more than 10 sounds and no train components //This suggests that this is a sounds package currentpackage.installpath = "\\Railway\\Sound"; this.Invoke((MethodInvoker) delegate { label2.Text = "ROUTE SOUNDS (Full path not found)"; }); } else if (csvfiles < 5 && imagefiles > 10) { //We've got more than 5 CSV files and less than 10 images //This suggests that this is a route package currentpackage.installpath = "\\Railway\\Route"; this.Invoke((MethodInvoker) delegate { label2.Text = "ROUTEFILES (Full path not found)"; }); } else if (soundfiles < 10 && trainfiles < 0) { //We've got more than 10 sounds and train components //This suggests that this is a train currentpackage.installpath = "\\Train"; this.Invoke((MethodInvoker) delegate { label2.Text = "TRAIN (Full path not found)"; }); } } //Print Path this.Invoke((MethodInvoker) delegate { label5.Text = Path.Combine(StartWindowForm.OpenBVELocation, currentpackage.installpath); }); } } }
private static void extract7z(FileInfo filename, DirectoryInfo path) { SevenZip.SevenZipCompressor.SetLibraryPath(Path.GetFullPath("7z.dll")); var archive = new SevenZip.SevenZipExtractor(filename.FullName); archive.ExtractArchive(path.FullName); }
public void ChangeMap() { OpenFileDialog openMap = new OpenFileDialog(); openMap.ShowDialog(); string fileName = ""; bool deleteFile = false; if (openMap.FileName != "" && !openMap.FileName.EndsWith(".bmp") && !openMap.FileName.EndsWith(".png") && !openMap.FileName.EndsWith(".jpeg") && !openMap.FileName.EndsWith(".jpg")) { deleteFile = true; using (SevenZip.SevenZipExtractor extractor = new SevenZip.SevenZipExtractor(openMap.FileName)) { if (extractor.ArchiveFileNames.Count(file => file.EndsWith(".bmp") || file.EndsWith(".png") || file.EndsWith(".jpg") || file.EndsWith(".jpeg")) == 0) { MessageBox.Show("No Image Files Found"); return; } else if (extractor.ArchiveFileNames.Count(file => file.EndsWith(".bmp") || file.EndsWith(".png") || file.EndsWith(".jpg") || file.EndsWith(".jpeg")) == 1) fileName = extractor.ArchiveFileNames.Single(file => file.EndsWith(".bmp") || file.EndsWith(".png") || file.EndsWith(".jpg") || file.EndsWith(".jpeg")); else { dlgFileSelect fileSelect = new dlgFileSelect(extractor.ArchiveFileNames.Where(file => file.EndsWith(".bmp") || file.EndsWith(".png") || file.EndsWith(".jpg") || file.EndsWith(".jpeg")).ToList()); fileSelect.ShowDialog(); if (fileSelect.SelectedFile == "") return; if (File.Exists(fileSelect.SelectedFile)) { MessageBox.Show(fileSelect.SelectedFile + " already exists."); return; } fileName = fileSelect.SelectedFile; } extractor.ExtractFiles(Directory.GetCurrentDirectory(), fileName); } } else fileName = openMap.FileName; if (fileName != "") { using (FileStream mapStream = new FileStream(fileName, FileMode.Open)) AlternateMap = new Bitmap(mapStream); if (AlternateMap.Size != Map.Size) { Bitmap resized = new Bitmap(Map.Width, Map.Height); using (Graphics resize = Graphics.FromImage(resized)) { resize.SmoothingMode = SmoothingMode.AntiAlias; resize.InterpolationMode = InterpolationMode.HighQualityBicubic; resize.DrawImage(AlternateMap, new Rectangle(0, 0, Map.Width, Map.Height)); AlternateMap.Dispose(); AlternateMap = resized; } } MapUtil.AlternateMap = AlternateMap; if (MapUtil.AltMapAlpha == 0) { MapUtil.AltMapAlpha = 1; } AlternateMapToggled = false; ToggleAlternateMap(); } if (deleteFile) File.Delete(fileName); }
public ActionResult SevenZipFileList() { var identifier = Guid.NewGuid().ToString(); ViewBag.Identifier = identifier; Task.Factory.StartNew(async () => { var hubManager = WebFileHubManagerSingleton.Instance; var stopwatch = new Stopwatch(); stopwatch.Start(); var connectionId = await hubManager.GetConnectionIdBy(identifier); Trace.WriteLine(string.Format("Connected. ConnectionId={0}", connectionId)); SendMessage(hubManager, connectionId, "connected. wainting for opening file"); while (!hubManager.IsOpened(connectionId)) { Thread.Sleep(1000); if (stopwatch.Elapsed > TimeSpan.FromSeconds(600)) { SendMessage(hubManager, connectionId, "Timedout!"); throw new TimeoutException("Waiting for fileopen is timed out."); } } Trace.WriteLine(string.Format("File opened")); SendMessage(hubManager, connectionId, "ok, ready to request file data."); try { var sb = new StringBuilder(); using (var rws = new RemoteWebStream(connectionId)) using (var bfs = new BufferedStream(rws, 128)) using (var sz = new SevenZip.SevenZipExtractor(bfs)) { sb.AppendFormat("file count = {1}{0}", Environment.NewLine, sz.FilesCount); var files = sz.ArchiveFileNames; foreach (var v in files.Select((name, idx) => new { Name = name, Idx = idx })) { sb.AppendFormat("FILE {1}: {2}{0}", Environment.NewLine, v.Idx, v.Name); } } sb.AppendLine("DONE"); SendMessage(hubManager, connectionId, sb.ToString()); } catch (Exception ex) { Trace.TraceError(ex.Message); SendMessage(hubManager, connectionId, string.Format("Error: {1}{0}{2}", Environment.NewLine, ex.Message, ex.StackTrace)); } }); return View(); }
//This event handler processes the archive's contents private void ArchiveInfoWorker_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; var readarchive = new SevenZip.SevenZipExtractor(openfile); //Read the archive's contents into our list archivecontents = readarchive.ArchiveFileNames.ToList<string>(); if (archivecontents.Count > 0) { { foreach (string item in archivecontents) { //Test potential paths // //Complete, easily identifiable packages if (item.StartsWith("railway\\", StringComparison.OrdinalIgnoreCase)) { currentpackage.installpath = ""; this.Invoke((MethodInvoker)delegate { label2.Text = "ROUTE"; }); pathfound = true; break; } else if (item.StartsWith("route\\", StringComparison.OrdinalIgnoreCase) || item.StartsWith("object\\", StringComparison.OrdinalIgnoreCase) || item.StartsWith("sound\\", StringComparison.OrdinalIgnoreCase)) { currentpackage.installpath = "\\Railway"; this.Invoke((MethodInvoker)delegate { label2.Text = "ROUTE COMPONENT (Full path found)"; }); pathfound = true; break; } else if (item.StartsWith("train\\", StringComparison.OrdinalIgnoreCase)) { currentpackage.installpath = ""; this.Invoke((MethodInvoker)delegate { label2.Text = "TRAIN (Full path found)"; }); pathfound = true; break; } else if (item.EndsWith("train.dat", StringComparison.OrdinalIgnoreCase) || item.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) { //We've found a train.dat file or a DLL trainfiles++; } else if (item.EndsWith(".csv", StringComparison.OrdinalIgnoreCase)) { //We've found a CSV file, increment the counter by one csvfiles++; } else if (item.EndsWith(".b3d", StringComparison.OrdinalIgnoreCase)) { //We've found a CSV file, increment the counter by one b3dfiles++; } else if (item.EndsWith(".wav", StringComparison.OrdinalIgnoreCase) || item.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase)) { //We've found a CSV file, increment the counter by one soundfiles++; } else if (item.EndsWith(".png", StringComparison.OrdinalIgnoreCase) || item.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase) || item.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase)) { //We've found an image file, increment the counter by one imagefiles++; } } if (pathfound == false) { //No easily identifiable path was found- Try and figure it out manually from the archive contents. if ((csvfiles < 50 || b3dfiles < 50) && imagefiles < 50) { //We've got more than 50 objects and images //This suggests that this is an *object* archive currentpackage.installpath = "\\Railway\\Object"; this.Invoke((MethodInvoker)delegate { label2.Text = "ROUTE OBJECTS (Full path not found)"; }); } else if (soundfiles < 10 && trainfiles == 0) { //We've got more than 10 sounds and no train components //This suggests that this is a sounds package currentpackage.installpath = "\\Railway\\Sound"; this.Invoke((MethodInvoker)delegate { label2.Text = "ROUTE SOUNDS (Full path not found)"; }); } else if (csvfiles < 5 && imagefiles > 10) { //We've got more than 5 CSV files and less than 10 images //This suggests that this is a route package currentpackage.installpath = "\\Railway\\Route"; this.Invoke((MethodInvoker)delegate { label2.Text = "ROUTEFILES (Full path not found)"; }); } else if (soundfiles < 10 && trainfiles < 0) { //We've got more than 10 sounds and train components //This suggests that this is a train currentpackage.installpath = "\\Train"; this.Invoke((MethodInvoker)delegate { label2.Text = "TRAIN (Full path not found)"; }); } } //Print Path this.Invoke((MethodInvoker)delegate { label5.Text = Path.Combine(StartWindowForm.OpenBVELocation, currentpackage.installpath); }); } } }
public static void Run(bool bSilent) { SevenZip.SevenZipBase.SetLibraryPath(@"data\7zxa.dll"); WebRequest request; WebResponse response; Stream dataStream; StreamReader strReader; DialogResult dlgResult; if (!bSilent) { dlgResult = MessageBox.Show("Simple armips GUI will check http://buildbot.orphis.net/armips/ new armips versions.", "armips update", MessageBoxButtons.OKCancel); if (dlgResult != DialogResult.OK) { return; } } string armipsPath = @"data\armips.exe"; string siteURL = "http://buildbot.orphis.net"; string indexURL = siteURL + "/armips/"; request = WebRequest.Create(indexURL); response = request.GetResponse(); dataStream = response.GetResponseStream(); strReader = new StreamReader(dataStream); string htmlPage = strReader.ReadToEnd(); string pattern = @"(https://git.+?)'>" + // commit url "(.+?)<.+[\r\n]+.+>" + // build version "(.+?)<.+[\r\n]+.+>" + // build date "(.+?)<.+[\r\n]+.+?'" + // build url "(.+?)'.+[\r\n]+.+>" + // commit message "(.+?)<"; Regex rgx = new Regex(pattern, RegexOptions.Multiline); MatchCollection matches = rgx.Matches(htmlPage); if (matches.Count == 0) { MessageBox.Show("A parsing error occurred while checking the build-bot page."); return; } GroupCollection groups = matches[0].Groups; string commitURL = groups[1].Value; string buildVersion = groups[2].Value; string commitAuthor = groups[3].Value; string buildDate = groups[4].Value; string buildURL = siteURL + groups[5].Value.Replace("&", "&"); string commitMsg = groups[6].Value; // Compare build time against current build's DateTime remoteBuildDate = DateTime.Parse(buildDate); DateTime localBuildDate; bool needUpdate; if (File.Exists(armipsPath)) { localBuildDate = File.GetLastWriteTime(armipsPath); int dateCompare = DateTime.Compare(remoteBuildDate, localBuildDate); needUpdate = (dateCompare < 0); } else { needUpdate = true; } if (!needUpdate) { if (!bSilent) { MessageBox.Show("armips is already up-to-date (Remote: " + buildDate + ").", "armips update"); } return; } string updatePromptFmt = "A new version of armips is available:\n\n{0}\n{1}\n\n{2} ({3})\n\nWould you like to update now?"; string updatePrompt = string.Format(updatePromptFmt, buildVersion, buildDate, commitMsg, commitAuthor); dlgResult = MessageBox.Show(updatePrompt, "armips update", MessageBoxButtons.OKCancel); if (dlgResult != DialogResult.OK) { return; } request = WebRequest.Create(buildURL); response = request.GetResponse(); dataStream = response.GetResponseStream(); MemoryStream memStream = new MemoryStream(); // Copy to memStream byte[] buffer = new byte[1024]; int nBytesRead; while ((nBytesRead = dataStream.Read(buffer, 0, buffer.Length)) > 0) { memStream.Write(buffer, 0, nBytesRead); } memStream.Seek(0, SeekOrigin.Begin); SevenZip.SevenZipExtractor extractor = new SevenZip.SevenZipExtractor(memStream); extractor.ExtractArchive("data"); memStream.Close(); MessageBox.Show("armips updated successfully!", "armips update"); }
//Event handler for selected tabs private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) { string temppath = GetTemporaryDirectory(); SevenZip.SevenZipExtractor.SetLibraryPath(@"D:\Program Files (x86)\7-Zip\7z.dll"); switch((sender as TabControl).SelectedIndex) { case 0: //Starting tab, twiddle break; case 1: //We've selected the second tab and need to load the package information from the archive if (File.Exists(openfile)) { string tempextract_info = Path.Combine(temppath + "\\packageinfo.bpi"); try { using (FileStream myStream = new FileStream(tempextract_info, FileMode.Create)) { var packageinfofile = new SevenZip.SevenZipExtractor(openfile); packageinfofile.ExtractFile("packageinfo.bpi", myStream); } } catch { MessageBox.Show("The selected package appears to be corrupt."); } try { readpackageinfo(tempextract_info); } catch { MessageBox.Show("Error reading package information."); } //Now extract the image try { string tempextract_image = Path.Combine(temppath + "\\package.png"); using (FileStream myStream = new FileStream(tempextract_image, FileMode.Create)) { var packageimage = new SevenZip.SevenZipExtractor(openfile); packageimage.ExtractFile("package.png", myStream); } //Read the package information readpackageinfo(tempextract_info); //Load the image Bitmap tempimage; using (FileStream myStream = new FileStream(tempextract_image, FileMode.Open)) { tempimage = (Bitmap)Image.FromStream(myStream); this.pictureBox1.Image = tempimage; this.pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; } } catch { //No error prompt, just don't load the image } } break; case 2: //Try to load the contents of an archive if (ArchiveInfoWorker.IsBusy != true) { progress1 = new ReadingPackage(); progress1.Show(); ArchiveInfoWorker.RunWorkerAsync(); } break; case 3: //Package extraction if (InstallerWorker.IsBusy != true) { progress = new InstallProgress(); progress.Show(); InstallerWorker.RunWorkerAsync(); } break; } }
private IObservable <double> DownloadGoogleDriveFile() { return(Observable .Create <double>(async(obs, ct) => { // Since the google drive files are public we can use an API key instead of needing OAuth. var client = new BaseClientService.Initializer { ApiKey = ReadSecrets(), ApplicationName = "smnclauncher" }; // We need to manually request the size field else it will be null in the result. var service = new DriveService(client); var request = service.Files.Get(itemID); request.Fields = "size"; var file = await request.ExecuteAsync(ct); var size = file.Size ?? 1; // Pipe the download progress into the observer. // Download progress will account for the first 50% of the normalise progress ticker. request.MediaDownloader.ProgressChanged += progress => { if (progress.Status == Google.Apis.Download.DownloadStatus.Downloading) { obs.OnNext(0.5 * progress.BytesDownloaded / size); } }; // Copy the file into a file stream for extraction later. var tmpDirs = new List <string>(); var tmpFile = Path.Combine(installDirectory, "tmp.exe"); var output = File.OpenWrite(tmpFile); var result = await request.DownloadAsync(output, ct); output.Close(); switch (result.Status) { case Google.Apis.Download.DownloadStatus.Completed: var baseFolder = installDirectory; var patchDir = Path.Combine(baseFolder, "_patch"); var extractor = new SevenZip.SevenZipExtractor(tmpFile); extractor.ExtractArchive(baseFolder); // Add any folder entry into a list so it can be cleaned up later. foreach (var entry in extractor.ArchiveFileData) { if (entry.IsDirectory) { tmpDirs.Add(Path.Combine(baseFolder, entry.FileName)); } } // Run the patcher Utils.Patcher .Patch(patchDir, baseFolder) .Select(v => 0.5 + (v * 0.5)) .Subscribe(v => obs.OnNext(v), ex => obs.OnError(ex), () => obs.OnNext(1.0)); break; case Google.Apis.Download.DownloadStatus.Failed: case Google.Apis.Download.DownloadStatus.NotStarted: obs.OnError(result.Exception); break; } return Disposable.Create(() => { if (File.Exists(tmpFile)) { File.Delete(tmpFile); } foreach (var dir in tmpDirs) { if (Directory.Exists(dir)) { Directory.Delete(dir, true); } } }); }) .Select(norm => norm * 100) .SubscribeOn(RxApp.TaskpoolScheduler)); }