/// <summary> /// Decompresses an archive. /// </summary> /// <param name="archive">Path for the archive</param> /// <param name="destination">Archive content destination folder.</param> /// <returns>True if no errors</returns> public static bool Decompress(string archive, string destination) { try { string archive_name = Path.GetFileNameWithoutExtension(archive); if(main.full_path_output) console.Write("Extracting " + archive + " to " + destination + " -> 0%", console.msgType.standard, false); else console.Write("Extracting " + archive_name + " to " + destination + " -> 0%", console.msgType.standard, false); SevenZipExtractor zip = new SevenZipExtractor(archive); zip.Extracting += Zip_Extracting; if (!main.overwrite) zip.FileExists += Zip_FileExists; if (main.create_dir) { zip.ExtractArchive(destination + @"\" + archive_name); } else zip.ExtractArchive(destination); Console.WriteLine(""); return true; } catch (Exception e) { Console.WriteLine(""); console.Write(e.Message +"("+archive+")", console.msgType.error); Log(e.ToString()); return false; } }
/// <summary> /// Extracts all files from the archive in one go. /// </summary> private void ExtractComplete(SevenZip.SevenZipExtractor extractor) { _unitsByte = false; UnitsTotal = 100; extractor.Extracting += (sender, e) => { UnitsProcessed = e.PercentDone; }; CancellationToken.ThrowIfCancellationRequested(); if (string.IsNullOrEmpty(SubDir)) { extractor.ExtractArchive(EffectiveTargetDir); } else { // Use an intermediate temp directory (on the same filesystem) string tempDir = Path.Combine(TargetDir, Path.GetRandomFileName()); extractor.ExtractArchive(tempDir); // Get only a specific subdir even though we extracted everything string subDir = FileUtils.UnifySlashes(SubDir); string tempSubDir = Path.Combine(tempDir, subDir); if (!FileUtils.IsBreakoutPath(subDir) && Directory.Exists(tempSubDir)) { new MoveDirectory(tempSubDir, EffectiveTargetDir, overwrite: true).Run(CancellationToken); } Directory.Delete(tempDir, recursive: true); } CancellationToken.ThrowIfCancellationRequested(); }
public override void Execute() { var libraryPath = Path.Combine(Path.GetDirectoryName(GetType().Assembly.Location), Environment.Is64BitProcess ? "7z64.dll" : "7z.dll"); SevenZipBase.SetLibraryPath(libraryPath); var targetPath = new FileInfo(Path.Combine(_cmdlet.SessionState.Path.CurrentFileSystemLocation.Path, _cmdlet.TargetPath)).FullName; var archiveFileName = new FileInfo(Path.Combine(_cmdlet.SessionState.Path.CurrentFileSystemLocation.Path, _cmdlet.ArchiveFileName)).FullName; var activity = String.Format("Extracting {0} to {1}", System.IO.Path.GetFileName(archiveFileName), targetPath); var statusDescription = "Extracting"; Write(String.Format("Extracting archive {0}", archiveFileName)); WriteProgress(new ProgressRecord(0, activity, statusDescription) { PercentComplete = 0 }); using (var extractor = new SevenZipExtractor(archiveFileName)) { extractor.Extracting += (sender, args) => WriteProgress(new ProgressRecord(0, activity, statusDescription) { PercentComplete = args.PercentDone }); extractor.FileExtractionStarted += (sender, args) => { statusDescription = String.Format("Extracting file {0}", args.FileInfo.FileName); Write(statusDescription); }; extractor.ExtractArchive(targetPath); } WriteProgress(new ProgressRecord(0, activity, "Finished") { RecordType = ProgressRecordType.Completed }); Write("Extraction finished"); }
public static void Extract(string file, string to) { using (var extractor = new SevenZipExtractor(file)) { extractor.ExtractArchive(to); } }
public void Update() { if (!IsUpdateAvailable()) { throw new LauncherException("no update is available"); } using (var mutex = new WurmAssistantMutex()) { mutex.Enter(1000, "You must close Wurm Assistant before running update"); var newFileZipped = WebApiClientSpellbook.GetFileFromWebApi( AppContext.WebApiBasePath, string.Format("{0}/{1}", AppContext.ProjectName, buildType), TimeSpan.FromSeconds(15), BasePath); using (var extractor = new SevenZipExtractor(newFileZipped.FullName)) { extractor.ExtractArchive(BasePath); } Thread.Sleep(1000); var cleaner = new DirCleaner(BasePath); cleaner.Cleanup(); } }
public override void Execute(DirectoryInfo targetDirectory, PortableEnvironment portableEnvironment) { // Decompress the file. SevenZipBase.SetLibraryPath(SevenZipLibPath); using (var extractor = new SevenZipExtractor(Path.Combine(targetDirectory.FullName, FileName))) extractor.ExtractArchive(targetDirectory.FullName); }
public FileReader(IFileStreamWrap stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); //Asses file ext var ext = Path.GetExtension(stream.Name); if (ext == ".gz") { Compression = CompressionScheme.GZip; } //Assign stream Stream = stream; //If not testing assign actual stream if (stream.FileStreamInstance != null) { if (Compression == CompressionScheme.None) { _reader = new StreamReaderWrap(stream.FileStreamInstance); } else if (Compression == CompressionScheme.GZip) { // Toggle between the x86 and x64 bit dll // var path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),Environment.Is64BitProcess ? "x64" : "x86", "7z.dll"); SevenZipExtractor.SetLibraryPath("C:\\Program Files (x86)\\7-Zip\\7z.dll"); _gzipStream = new SevenZipExtractor(stream.FileStreamInstance); //_memoryStream = new MemoryStream(); //_gzipStream.ExtractFile(0, _memoryStream); _gzipStream.ExtractArchive("D:\\test.txt"); _reader = new StreamReaderWrap(_memoryStream); } } }
public static void extract(string fileName, string directory) { SevenZipExtractor.SetLibraryPath("7z.dll"); SevenZipExtractor extractor = new SevenZipExtractor(fileName); extractor.Extracting += new EventHandler<ProgressEventArgs>(extr_Extracting); extractor.FileExtractionStarted += new EventHandler<FileInfoEventArgs>(extr_FileExtractionStarted); extractor.ExtractionFinished += new EventHandler<EventArgs>(extr_ExtractionFinished); extractor.ExtractArchive(directory); }
internal DirectoryHandle CreateByUnzippingFile(string zipFilePath) { var dir = CreateTempDirectory(); zipFilePath = AbsolutizePath(zipFilePath); var extractor = new SevenZipExtractor(File.OpenRead(zipFilePath)); extractor.ExtractArchive(dir.FullName); return new DirectoryHandle(this, dir); }
public void Unpack(string outputPath) { SevenZipExtractor tmp = new SevenZipExtractor(_targetPath); tmp.FileExtractionStarted += new EventHandler<IndexEventArgs>((s, e) => { Console.WriteLine(String.Format("[{0}%] {1}", e.PercentDone, tmp.ArchiveFileData[e.FileIndex].FileName)); }); tmp.ExtractionFinished += new EventHandler((s, e) => {Console.WriteLine("Finished!");}); tmp.ExtractArchive(outputPath); }
static public void extract(string fileName, string directory) { SevenZipExtractor.SetLibraryPath("7z.dll"); try { SevenZipExtractor extractor = new SevenZipExtractor(fileName); extractor.Extracting += new EventHandler<ProgressEventArgs>(extr_Extracting); extractor.FileExtractionStarted += new EventHandler<FileInfoEventArgs>(extr_FileExtractionStarted); extractor.ExtractionFinished += new EventHandler<EventArgs>(extr_ExtractionFinished); extractor.ExtractArchive(directory); } catch (System.IO.FileNotFoundException e) { MessageBox.Show(e.Message); } }
/// <summary> /// 解壓 /// </summary> /// <param name="archiveName"></param> /// <param name="exportFolder"></param> public static void ExtractFiles(string archiveName, string exportFolder) { string sFile = System.IO.Path.Combine(Environment.CurrentDirectory, "7z.dll"); SevenZip.SevenZipCompressor.SetLibraryPath(sFile); string fileExt = System.IO.Path.GetExtension(archiveName).ToLower(); if (fileExt == ".7z" || fileExt == ".zip" || fileExt == ".rar") { //Can not load 7-zip library or internal COM error! Message: DLL file does not exist. var extractor = new SevenZip.SevenZipExtractor(archiveName); extractor.ExtractArchive(exportFolder); } }
public List<GrepSearchResult> Search(string file, string searchPattern, SearchType searchType, GrepSearchOption searchOptions, Encoding encoding) { List<GrepSearchResult> searchResults = new List<GrepSearchResult>(); SevenZipExtractor extractor = new SevenZipExtractor(file); GrepEnginePlainText plainTextEngine = new GrepEnginePlainText(); plainTextEngine.Initialize(new GrepEngineInitParams(showLinesInContext, linesBefore, linesAfter, fuzzyMatchThreshold)); string tempFolder = Utils.FixFolderName(Utils.GetTempFolder()) + "dnGREP-Archive\\" + Utils.GetHash(file) + "\\"; if (Directory.Exists(tempFolder)) Utils.DeleteFolder(tempFolder); Directory.CreateDirectory(tempFolder); try { extractor.ExtractArchive(tempFolder); foreach (string archiveFileName in Directory.GetFiles(tempFolder, "*.*", SearchOption.AllDirectories)) { IGrepEngine engine = GrepEngineFactory.GetSearchEngine(archiveFileName, new GrepEngineInitParams(showLinesInContext, linesBefore, linesAfter, fuzzyMatchThreshold)); var innerFileResults = engine.Search(archiveFileName, searchPattern, searchType, searchOptions, encoding); using (FileStream reader = File.Open(archiveFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (StreamReader streamReader = new StreamReader(reader)) { foreach (var result in innerFileResults) { if (!result.HasSearchResults) result.SearchResults = Utils.GetLinesEx(streamReader, result.Matches, linesBefore, linesAfter); } } searchResults.AddRange(innerFileResults); } foreach (GrepSearchResult result in searchResults) { result.FileNameDisplayed = file + "\\" + result.FileNameDisplayed.Substring(tempFolder.Length); result.FileNameReal = file; result.ReadOnly = true; } } catch (Exception ex) { logger.LogException(LogLevel.Error, "Failed to search inside archive.", ex); } return searchResults; }
private string extractBundledResourcesFromFile(string filename) { string sourceFile = Path.Combine(resourcesDir, "bundled", filename); string timestampFile = Path.Combine(extractedResourcesDir, Path.ChangeExtension(filename, "timestamp")); string destinationDir = Path.Combine(extractedResourcesDir, Path.GetFileNameWithoutExtension(filename)); if (!File.Exists(timestampFile) || File.GetLastWriteTimeUtc(sourceFile) > File.GetLastWriteTimeUtc(timestampFile)) { DeleteRecursivelyWithMagicDust(destinationDir); var extractor = new SevenZipExtractor(sourceFile); // we typically have a properly-named root dir inside .7z itself, so extracting into destinationDir doesn't work extractor.ExtractArchive(extractedResourcesDir); extractor.Dispose(); File.WriteAllBytes(timestampFile, new byte[0]); } return destinationDir; }
protected override void BeginTask(object state) { ExtractionTask task = (ExtractionTask)state; Exception exception = null; try { if (!CancelRequested) { task.OnProgressStarted(this, new ProgressStartedEventArgs(task)); } SevenZipExtractor extractor = new SevenZipExtractor(task.Archive); extractor.Extracting += new EventHandler<SevenZip.ProgressEventArgs>(delegate(object sender, SevenZip.ProgressEventArgs e) { if (!CancelRequested) { task.OnProgressUpdate(this, new ProgressUpdateEventArgs(task, e.PercentDone, 100)); } }); extractor.ExtractArchive(task.Destination); } catch (Exception e) { exception = e; } finally { if (!CancelRequested) { task.OnProgressCompleted(this, new ProgressCompletedEventArgs(exception, CancelRequested, task, 100, 100)); } } base.BeginTask(state); }
public void Extract(string archivePath, string installPath, List<ManifestFile> files) { this.SetLibraryPath(); int progress = 0; var thread = new Thread(() => { var extractor = new SevenZipExtractor(archivePath); extractor.ExtractionFinished += ExtractionFinished; extractor.FileExtractionFinished += (sender, e) => { progress++; this.progressNotifier.UpdateProgress(ProgressStage.ExtractFilesFromPackage, files.Count, progress); }; extractor.ExtractArchive(installPath); }); thread.Start(); thread.Join(); }
public static String pptxParser(String filename) { //path to the systems temporary folder String tempFolderPath = Path.GetTempPath(); tempFolderPath += "excelTemp\\"; //create a directory to dump everything into inside the temp folder Directory.CreateDirectory(tempFolderPath); //set the path of the 7z.dll (it needs to be in the debug folder) SevenZipExtractor.SetLibraryPath("7z.dll"); SevenZipExtractor extractor = new SevenZipExtractor(filename); //Extract the entrie excel file extractor.ExtractArchive(tempFolderPath); extractor.Dispose(); //Count how many slides there are in the presentation int count = Directory.GetFiles(tempFolderPath + "ppt\\slides", "*.xml", SearchOption.TopDirectoryOnly).Length; //Create an array of filenames based off how many slides we counted String[] files = new String[count]; for (int i = 1; i <= count; i++) { files[i - 1] = "ppt\\slides\\slide" + i + ".xml"; } //send the slides to the xml parser String result = ""; foreach (String s in files) result += " " + XMLParser.Parser.ParseXMLtoString(tempFolderPath + s); //delete the temporary directory we created at the beginning Directory.Delete(tempFolderPath, true); return result; }
public void ExtractionTestCancelFeature(){ using (var tmp = new SevenZipExtractor(Path.Combine(archivePath, "Test.lzma.7z"))) { tmp.FileExtractionStarted += (s, e) =>{ if (e.FileInfo.Index == 10) { e.Cancel = true; TestContext.WriteLine("Cancelled"); } else TestContext.WriteLine(String.Format("[{0}%] {1}", e.PercentDone, e.FileInfo.FileName)); }; tmp.FileExists += (o, e) => TestContext.WriteLine("Warning: file \"" + e.FileName + "\" already exists."); tmp.ExtractionFinished += (s, e) => TestContext.WriteLine("Finished!"); tmp.ExtractArchive(tempFolder); } }
public void ExtractionTestMultiVolumes(){ using (var tmp = new SevenZipExtractor(Path.Combine(archivePath, "Test.part1.rar"))) tmp.ExtractArchive(tempFolder); }
public void StreamingSFXExtractionTest() { using ( var tmp = new SevenZipExtractor( File.OpenRead(Path.Combine(archivePath, "Test.7Zip.LZMA2.sfx.exe")) ) ) { tmp.FileExtractionStarted += (s, e) => TestContext.WriteLine(String.Format("[{0}%] {1}", e.PercentDone, e.FileInfo.FileName)); tmp.ExtractionFinished += (s, e) => TestContext.WriteLine("Finished!"); tmp.ExtractArchive(tempFolder); } }
public async Task MultiTaskedExtractionTest(){ throw new NotImplementedException("See TaskedExtractionTest, please"); var tasks = new[]{ Task.Factory.StartNew(() =>{ using (var tmp = new SevenZipExtractor(Path.Combine(archivePath, "Test.lzma.7z"))) { tmp.FileExtractionStarted += (s, e) => TestContext.WriteLine(String.Format("[{0}%] {1}", e.PercentDone, e.FileInfo.FileName)); tmp.ExtractionFinished += (s, e) => TestContext.WriteLine("Finished!"); tmp.ExtractArchive(Path.Combine(tempFolder, "MultiThreadedExtractionTest1")); } }), Task.Factory.StartNew(() =>{ using (var tmp = new SevenZipExtractor(Path.Combine(archivePath, "Test.lzma.7z"))) { tmp.FileExtractionStarted += (s, e) => TestContext.WriteLine(String.Format("[{0}%] {1}", e.PercentDone, e.FileInfo.FileName)); tmp.ExtractionFinished += (s, e) => TestContext.WriteLine("Finished!"); tmp.ExtractArchive(Path.Combine(tempFolder, "MultiThreadedExtractionTest2")); } }) }; await Task.WhenAll(tasks); }
public async Task TaskedExtractionTest(){ throw new NotImplementedException("Read code comments carefully, please"); await Task.Factory.StartNew(() =>{ using (var tmp = new SevenZipExtractor(Path.Combine(archivePath, "Test.lzma.7z"))) { /* bug: here is heisenbug, throws exception, nobody knows why looks like heap corruption if you stil sure that the bug is in WriteLine, try to comment it out and you will se bug in another place... also MultiThreadedExtractionTest works fine YOU NEED RATHER BIG FILE TO REPRODUCE THIS BUG, SMALL FILES AS Test.lzma.7z don't cause the crash */ tmp.FileExtractionStarted += (s, e) => TestContext.WriteLine(String.Format("[{0}%] {1}", e.PercentDone, e.FileInfo.FileName)); tmp.ExtractionFinished += (s, e) => TestContext.WriteLine("Finished!"); tmp.ExtractArchive(Path.Combine(tempFolder, "MultiThreadedExtractionTest1")); } }); }
public void MultiThreadedExtractionTest(){ var t1 = new Thread(() =>{ using (var tmp = new SevenZipExtractor(Path.Combine(archivePath, "Test.lzma.7z"))) { tmp.FileExtractionStarted += (s, e) => TestContext.WriteLine(String.Format("[{0}%] {1}", e.PercentDone, e.FileInfo.FileName)); tmp.ExtractionFinished += (s, e) => TestContext.WriteLine("Finished!"); tmp.ExtractArchive(Path.Combine(tempFolder, "MultiThreadedExtractionTest1")); } }); var t2 = new Thread(() =>{ using (var tmp = new SevenZipExtractor(Path.Combine(archivePath, "Test.lzma.7z"))) { tmp.FileExtractionStarted += (s, e) => TestContext.WriteLine(String.Format("[{0}%] {1}", e.PercentDone, e.FileInfo.FileName)); tmp.ExtractionFinished += (s, e) => TestContext.WriteLine("Finished!"); tmp.ExtractArchive(Path.Combine(tempFolder, "MultiThreadedExtractionTest2")); } }); t1.Start(); t2.Start(); t1.Join(); t2.Join(); }
private void DownloadBuild(string url, int index) { // Windows will throw an error if you have the folder you're trying to delete open in // explorer. It will remove the contents but error out on the folder removal. That's // good enough but this is just so it doesn't crash. try { if (Directory.Exists(@"dolphin")) Directory.Delete(@"dolphin", true); } catch (IOException) { } using (WebClient client = new WebClient()) using (var download_finished = new ManualResetEvent(false)) { client.DownloadProgressChanged += (s, e) => { m_form.ChangeProgressBar(e.ProgressPercentage, string.Format("Downloading build {0}-{1}", s_major_version, m_build_list[index])); }; client.DownloadFileCompleted += (s, e) => { // Known Bug: Sometimes the label doesn't get updated before it extracts and // launches. I want to blame this meh-level 7z lib blocking something. SevenZipExtractor dolphin_zip = new SevenZipExtractor(@"dolphin.7z"); dolphin_zip.Extracting += (sender, eventArgs) => m_form.ChangeProgressBar(eventArgs.PercentDone, "Extracting and launching"); dolphin_zip.ExtractArchive("dolphin"); download_finished.Set(); }; client.DownloadFileAsync(new Uri(url), "dolphin.7z"); download_finished.WaitOne(); } }
private async void unzip(string path) { progressBar1.Minimum = 0; progressBar1.Maximum = 100; progressBar1.Value = 0; progressBar1.Visible = true; var progressHandler = new Progress <byte>( percentDone => progressBar1.Value = percentDone); var progress = progressHandler as IProgress <byte>; var sevenZipPath = Path.Combine( Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "7za.dll"); SevenZipBase.SetLibraryPath(sevenZipPath); var file = new SevenZip.SevenZipExtractor(path); file.Extracting += (sender, args) => { progress.Report(args.PercentDone); }; file.ExtractionFinished += (sender, args) => { // Do stuff when done loadlbl.Text = "Successfully Fixed!"; try { if (File.Exists(Path.Combine(System.IO.Path.GetTempPath(), @"ddf.bin1"))) { File.Delete(Path.Combine(System.IO.Path.GetTempPath(), @"ddf.bin1")); } if (File.Exists(Path.Combine(System.IO.Path.GetTempPath(), @"ddf.bin2"))) { File.Delete(Path.Combine(System.IO.Path.GetTempPath(), @"ddf.bin2")); } if (File.Exists(Path.Combine(System.IO.Path.GetTempPath(), @"ddf.7z"))) { File.Delete(Path.Combine(System.IO.Path.GetTempPath(), @"ddf.7z")); } } catch (SystemException) { } KryptonMessageBox.Show("Operation Success! This was easier than we thought.. ROFL"); this.Close(); }; //Extract the stuff string xpath = Path.Combine(AoE2GamePath, @"Data"); try { file.ExtractArchive(xpath); file.Dispose(); } catch (SystemException) { } }
private void Extract() { //setup settings. foreach (var fullPath in _fileAndDirectoryFullPaths) { _sevenZipExtractor = new SevenZipExtractor(fullPath); _sevenZipExtractor.PreserveDirectoryStructure = true; _sevenZipExtractor.Extracting += Compressing; _sevenZipExtractor.FileExtractionStarted += FileExtractionStarted; _sevenZipExtractor.ExtractionFinished += CompressionFinished; _sevenZipExtractor.FileExtractionFinished += FileExtractionFinished; //Extract files _sevenZipExtractor.ExtractArchive(_archivePath); } Done(); }
/// <summary> /// Download a package from blob storage and unzip it /// </summary> /// <param name="containerName">The Blob storage container name</param> /// <param name="packageName">The name of the zip file package</param> /// <param name="workingDirectory">Where to extract the files</param> private void InstallPackage(string containerName, string packageName, string workingDirectory) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue(DATA_CONNECTION_STRING)); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(containerName); CloudBlockBlob blob = container.GetBlockBlobReference(packageName); Tracer.WriteLine(string.Format("Downloading {0} to {1}", blob.Uri, workingDirectory), "Information"); using (MemoryStream stream = new MemoryStream()) { blob.DownloadToStream(stream); Tracer.WriteLine(string.Format("Extracting {0}", packageName), "Information"); using (SevenZipExtractor extractor = new SevenZipExtractor(stream)) { // set 7zip dll path string sevenZipPath = Path.Combine(Directory.GetCurrentDirectory(), @"Redist\7z64.dll"); SevenZipExtractor.SetLibraryPath(sevenZipPath); extractor.ExtractArchive(workingDirectory); } } Tracer.WriteLine("Extraction finished", "Information"); }
/// <summary> /// Extracts data from a .zip archive. /// </summary> /// <param name="targetDir">The directory to put the extracted data in.</param> /// <param name="zipFile">The file to extract data from.</param> public static void UnzipFile(string targetDir, string zipFile) { SetupZlib(); using (SevenZipExtractor extractor = new SevenZipExtractor(zipFile)) { extractor.ExtractArchive(targetDir); } }
private void DownloadBuild(string url, int index) { // Windows will throw an error if you have the folder you're trying to delete open in // explorer. It will remove the contents but error out on the folder removal. That's // good enough but this is just so it doesn't crash. try { if (Directory.Exists(@"dolphin")) Directory.Delete(@"dolphin", true); } catch (IOException) { } using (WebClient client = new WebClient()) { client.DownloadFileAsync(new Uri(url), "dolphin.7z"); client.DownloadProgressChanged += (s, e) => { m_form.ChangeProgressBar(e.ProgressPercentage, "Downloading build " + m_build_list.ElementAt(index)); }; client.DownloadFileCompleted += (s, e) => { // Known Bug: Sometimes the label doesn't get updated before it extracts and // launches. I want to blame this meh-level 7z lib blocking something. m_form.ChangeProgressBar(0, "Extracting and launching"); SevenZipExtractor dolphin_zip = new SevenZipExtractor(@"dolphin.7z"); dolphin_zip.ExtractArchive("dolphin"); m_download_complete = true; }; } while (!m_download_complete) { Application.DoEvents(); } m_download_complete = false; }
public void UpdateFiles() { List<FileItem> files = new List<FileItem>(); List<FileItem> filesDownload = new List<FileItem>(); FileInfo fileinfo = new FileInfo(_updatePath); foreach (FileCollection col in _downloadcollections) { files.AddRange(col.Files); } AddToLog(files.Count + " files marked for check."); _progressVerify.Maximum = files.Count; _progressVerify.Value = 0; _progressTotalDownload.Value = 0; _progressFileDownload.Value = 0; if (Library.SystemSettings.isDebuggingEnabled) { this.AddToLog("Starting file check", false); } foreach (FileItem f in files) { //build the stringname string FullPath = fileinfo.DirectoryName + f.Directory + f.Filename; if (File.Exists(FullPath)) { //initiate a CRC object CRC32 crc = new CRC32(); //check debug settings if (Library.SystemSettings.isDebuggingEnabled) { this.AddToLog(" File: " + FullPath); } else { this.AddToLog(f.Directory + f.Filename); } //the file crc string fileCRC = ""; //open a link to the file using (Stream reader = new FileStream(FullPath, FileMode.Open, FileAccess.Read)) { //go though each byte foreach (byte b in crc.ComputeHash(reader)) { //build the crc string fileCRC += b.ToString("x2").ToLower(); } } //check debug settings if (Library.SystemSettings.isDebuggingEnabled) { this.AddToLog("System CRC: " + fileCRC); this.AddToLog(" XML CRC: " + f.FileCRC); } //check if they are matching if (fileCRC != f.FileCRC) { filesDownload.Add(f); if (Library.SystemSettings.isDebuggingEnabled) { this.AddToLog(" Status: Marked for download"); this.AddToLog("", false); } } else { if (Library.SystemSettings.isDebuggingEnabled) { this.AddToLog(" Status: No action required"); this.AddToLog("", false); } } } else { filesDownload.Add(f); if (Library.SystemSettings.isDebuggingEnabled) { this.AddToLog(" File: " + FullPath); this.AddToLog(" Status: Marked for download"); this.AddToLog("", false); } else { this.AddToLog(f.Directory + f.Filename); } } _progressVerify.Value += 1; } _progressTotalDownload.Maximum = filesDownload.Count; _progressTotalDownload.Value = 0; if (Library.SystemSettings.isDebuggingEnabled) { this.AddToLog("", false); this.AddToLog("Starting file download."); } this.AddToLog(filesDownload.Count + " files marked for download."); foreach (FileItem f in filesDownload) { //Build the pathstring string FullDirPath = fileinfo.DirectoryName + f.Directory; string FullFilePath = FullDirPath + f.Filename; using (WebClient webClient = new WebClient()) { //initiate a CRC object CRC32 crc = new CRC32(); webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged); try { string url = (webRepository + f.Directory + f.Filename).Replace('\\', '/'); if (!Directory.Exists(FullDirPath)) { Directory.CreateDirectory(FullDirPath); } this.AddToLog("Downloading " + f.Directory + f.Filename + ".7z"); webClient.DownloadFileAsync(new Uri(url), FullFilePath+".7z"); if (Library.SystemSettings.isDebuggingEnabled) { this.AddToLog(" Waiting for download to finish"); } while (webClient.IsBusy) { } if (Library.SystemSettings.isDebuggingEnabled) { this.AddToLog(" Download finished"); } //start deflateing the file SevenZipExtractor.SetLibraryPath("7z.dll"); SevenZipExtractor zip = new SevenZipExtractor(FullFilePath + ".7z"); if (File.Exists(FullFilePath + ".7z")) { //make sure the CRC is new CRC32 crc2 = new CRC32(); //the file crc string fileCRC = ""; //log this.AddToLog("Checking local archive CRC..."); //open a link to the file using (Stream reader = new FileStream(FullFilePath + ".7z", FileMode.Open, FileAccess.Read)) { //go though each byte foreach (byte b in crc2.ComputeHash(reader)) { //build the crc string fileCRC += b.ToString("x2").ToLower(); } } if (f.ArchiveCRC == fileCRC) { try { if (Library.SystemSettings.isDebuggingEnabled) { this.AddToLog("Extracting :" + FullFilePath + ".7z"); } zip.ExtractArchive(FullDirPath); if (File.Exists(FullFilePath)) { //make sure the CRC is new CRC32 crc3 = new CRC32(); //the file crc fileCRC = ""; this.AddToLog("Checking local file CRC..."); //open a link to the file using (Stream reader = new FileStream(FullFilePath, FileMode.Open, FileAccess.Read)) { //go though each byte foreach (byte b in crc3.ComputeHash(reader)) { //build the crc string fileCRC += b.ToString("x2").ToLower(); } } //check if they are matching if (fileCRC != f.FileCRC) { this.AddToLog("[Error] File CRC did't match expected crc."); File.Delete(FullFilePath); //check debug settings if (Library.SystemSettings.isDebuggingEnabled) { this.AddToLog("System CRC: " + fileCRC); this.AddToLog(" XML CRC: " + f.FileCRC); } } } else { this.AddToLog("[Error] Unable to locate extracted file."); this.AddToLog("[Error] Local : " + FullFilePath); this.AddToLog("[Error] Remote: " + url); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } else { this.AddToLog("[Error] CRC on local archive dosen't match."); this.AddToLog("[Error] System CRC: " + fileCRC); this.AddToLog("[Error] XML CRC: " + f.FileCRC); } //clean up after ourselves. File.Delete(FullFilePath + ".7z"); } } catch (WebException ex) { this.AddToLog("Error: " + ex.Message); } } _progressTotalDownload.Value += 1; } this.AddToLog(""); this.AddToLog("System update finished.."); if (this.LoggingArea.Text.Contains("error")) { this.AddToLog("The log contains errors, please check the error log."); this.AddToLog("If the system have made an CRC error, please try"); this.AddToLog("updateing the system again. If the error persist then"); this.AddToLog("please notify me though mail ([email protected])"); this.AddToLog(" or PM on the forum (msjohansen / Mark Johansen)"); } this.AddToLog(""); this.AddToLog("Did you have problems? try hitting F8 and try again."); }
protected override void ExecuteCore() { SevenZipExtractor extractor = null; try { string directory = Target.Replace('/', '\\'), filePath = FileHelper.GetFilePath(directory), dataPath = FileHelper.GetDataPath(directory); if (!Directory.Exists(filePath)) Directory.CreateDirectory(filePath); if (!Directory.Exists(dataPath)) Directory.CreateDirectory(dataPath); extractor = new SevenZipExtractor(FileHelper.GetFilePath(Source)); var singleFileName = extractor.ArchiveFileNames.Count == 1 && extractor.ArchiveFileNames[0] == "[no name]" ? Path.GetFileNameWithoutExtension(Source) : null; FileCount = extractor.FilesCount; FileLength = extractor.ArchiveFileData.Sum(data => (long)data.Size); long nextLength = 0, nextFile = 0; extractor.FileExtractionStarted += (sender, e) => { ProcessedFileCount += nextFile; ProcessedFileLength += nextLength; nextLength = (long)e.FileInfo.Size; nextFile = 1; StartFile(FileHelper.Combine(directory, singleFileName ?? e.FileInfo.FileName)); }; extractor.FileExtractionFinished += (sender, e) => FinishFile(FileHelper.Combine(directory, singleFileName ?? e.FileInfo.FileName)); extractor.ExtractArchive(filePath); Finish(); } catch (SevenZipException) { if (extractor == null) throw; throw new AggregateException(extractor.Exceptions); } }
void DoWork() { //This code is fine. Fine I say. try { //find latest installed version SetStatus("Checking latest local version"); SetDesc(""); bool previousVersionAvailable = false; bool failed = false; var workdir = GeneralHelper.PathCombineWithCodeBasePath(null); var dirInfo = new DirectoryInfo(workdir); var existingWaDirs = dirInfo.GetDirectories(); Version localLatestVersion = null; foreach (var dir in existingWaDirs) { Match match = Regex.Match(dir.Name, @"WurmAssistant_(\d+)_(\d+)_(\d+)_(\d+)", RegexOptions.IgnoreCase); if (match.Success) { var thisVersion = new Version( int.Parse(match.Groups[1].Value), int.Parse(match.Groups[2].Value), int.Parse(match.Groups[3].Value), int.Parse(match.Groups[4].Value)); if (localLatestVersion == null || thisVersion > localLatestVersion) { localLatestVersion = thisVersion; } } } if (localLatestVersion == null) { SetDesc("No installed Wurm Assistant found, attempting to download latest..."); } else { previousVersionAvailable = true; } //check for new assistant version, timeout should be ~20 sec SetStatus("Checking for new Wurm Assistant version"); const int maxRetries = 3; int retries = maxRetries; HttpResponseMessage response = null; while (retries != 0) { var client = new HttpClient { BaseAddress = new Uri(BasePath), Timeout = GetTimeout(maxRetries - retries + 1) }; try { response = client.GetAsync(ControllerPath).Result; if (!response.IsSuccessStatusCode) { retries--; SetDesc("Failed contacting remote server: " + response.StatusCode + " => " + response.ReasonPhrase); AllowRunningPrevious(); } else { AllowRunningPrevious(false); break; } } catch (AggregateException agExc) { retries--; string error = "Failed contacting remote server: " + string.Join(", ", agExc.InnerExceptions.Select(x => x.Message)); SetDesc(error); LogException(agExc); AllowRunningPrevious(); } if (retries != 0) { SetDesc(string.Format("Retrying... ({0} of {1})", maxRetries - retries, maxRetries - 1), true); } } if (response == null) { SetFailure("Update failed", allowPreviousVersion: previousVersionAvailable); return; } var obj = response.Content.ReadAsStringAsync().Result; var array = JsonConvert.DeserializeObject<string[]>(obj); //var array = new[] {"WurmAssistant_2_0_81_0.zip"}; if (array.Length == 0) { SetFailure("Update failed, no WA version on download server.", allowPreviousVersion: true); return; } var remoteLatestVersion = new Version(); string remoteFileName = null; foreach (var fileString in array) { Match match = Regex.Match(fileString, @"WurmAssistant_(\d+)_(\d+)_(\d+)_(\d+)", RegexOptions.IgnoreCase); if (match.Success) { var thisVersion = new Version( int.Parse(match.Groups[1].Value), int.Parse(match.Groups[2].Value), int.Parse(match.Groups[3].Value), int.Parse(match.Groups[4].Value)); if (thisVersion > remoteLatestVersion) { remoteLatestVersion = thisVersion; remoteFileName = fileString; } } } if (localLatestVersion == null || remoteLatestVersion > localLatestVersion) { //update SetStatus("Downloading new Wurm Assistant version (" + remoteLatestVersion + ")"); SetProgressBarToBlocks(); const int maxTries = 3; int currentTry = 1; string downloadPath = GeneralHelper.PathCombineWithCodeBasePath(remoteFileName); while (currentTry <= maxTries) { try { using (var webclient = new WebDownload((int)(GetTimeout(currentTry).TotalMilliseconds))) { var tcs = new TaskCompletionSource<bool>(); webclient.DownloadProgressChanged += (sender, args) => SetProgressBar(args.BytesReceived, args.TotalBytesToReceive); webclient.DownloadFileCompleted += (sender, args) => tcs.SetResult(true); webclient.DownloadFileAsync( new Uri(BasePath + ControllerPath + string.Format(RequestTemplate, remoteFileName)), downloadPath); tcs.Task.Wait(); AllowRunningPrevious(false); } break; } catch (Exception ex) { SetDesc("Error while downloading new version: " + ex.Message); currentTry++; if (currentTry <= maxTries) { SetDesc("\r\n" + string.Format("Retrying... ({0} of {1})", currentTry - 1, maxTries - 1), true); AllowRunningPrevious(); } else { SetFailure("Download failed", allowPreviousVersion: previousVersionAvailable); failed = true; var fileinfo = new FileInfo(downloadPath); if (fileinfo.Exists) { try { fileinfo.Delete(); } catch (Exception ex2) { SetDesc("failed to clean the partially downloaded file: " + downloadPath + "\r\n" + ex2.Message); LogException(ex2); } } break; } } } //extract if (!failed) { SetStatus("Extracting new Wurm Assistant version"); try { var tempExtractDir = new DirectoryInfo(GeneralHelper.PathCombineWithCodeBasePath("temp")); //clean up any past failed updates if (tempExtractDir.Exists) { Thread.Sleep(100); tempExtractDir.Delete(true); } Thread.Sleep(200); tempExtractDir.Create(); Thread.Sleep(200); using (var extractor = new SevenZipExtractor(downloadPath)) { extractor.ExtractArchive(tempExtractDir.FullName); } var waDirName = Path.GetFileNameWithoutExtension(downloadPath); var newAssistantDir = new DirectoryInfo(Path.Combine(tempExtractDir.FullName, waDirName)); var destinationPath = GeneralHelper.PathCombineWithCodeBasePath(waDirName); const int maxMoveTries = 100; int currentMoveTry = 0; Thread.Sleep(500); while (true) { currentMoveTry++; try { newAssistantDir.MoveTo(destinationPath); AllowRunningPrevious(false); break; } catch (IOException) { if (currentMoveTry > maxMoveTries) { throw; } else if (currentMoveTry == 20) { AllowRunningPrevious(); } else { SetDesc("IOException while moving new WA dir, retrying... (" + currentMoveTry + ")"); } } Thread.Sleep(200); } //cleanup var downloadedZip = new FileInfo(downloadPath); if (downloadedZip.Exists) { try { downloadedZip.Delete(); } catch (Exception ex2) { SetDesc("failed to clean the partially downloaded file: " + downloadPath + "\r\n" + ex2.Message, true); } } try { tempExtractDir.Delete(true); } catch (Exception ex3) { SetDesc("failed to clean temp dir: " + tempExtractDir.FullName + "\r\n" + ex3.Message, true); LogException(ex3); } //clean old versions foreach (var dir in existingWaDirs) { try { dir.Delete(true); } catch (Exception ex) { Logger.LogDiag("error while deleting old WA dir", this, ex); } } } catch (Exception ex) { SetFailure("Extracting failed", "Error while trying to extract archive: " + ex.Message + "\r\n\r\nTry to run launcher again " + (previousVersionAvailable ? " or start previous version" : ""), previousVersionAvailable); failed = true; LogException(ex); } } } if (!failed) RunLatestVersion(); } catch (AggregateException agExc) { string error = "Unexpected errors while running launcher: " + string.Join(",", agExc.InnerExceptions.Select(x => x.Message)); SetFailure("Launching failed", error); LogException(agExc); } catch (Exception exception) { SetFailure("Launching failed", "Unexpected error while running launcher: " + exception.Message); LogException(exception); } }
public static bool Import(string importPath) { try { Set7ZipLibraryPath(); using (SevenZipExtractor zip = new SevenZipExtractor(importPath)) { zip.ExtractArchive(Program.PersonalFolder); return true; } } catch (Exception e) { DebugHelper.WriteException(e); MessageBox.Show("Error while importing backup:\r\n\r\n" + e, "ShareX - Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return false; }