/// <summary> /// Extracts files from the archive one-by-one. /// </summary> private void ExtractIndividual(SevenZip.SevenZipExtractor extractor) { _unitsByte = true; UnitsTotal = extractor.UnpackedSize; foreach (var entry in extractor.ArchiveFileData) { string relativePath = GetRelativePath(entry.FileName.Replace('\\', '/')); if (relativePath == null) { continue; } if (entry.IsDirectory) { CreateDirectory(relativePath, entry.LastWriteTime); } else { using (var stream = OpenFileWriteStream(relativePath)) extractor.ExtractFile(entry.Index, stream); File.SetLastWriteTimeUtc(CombinePath(relativePath), DateTime.SpecifyKind(entry.LastWriteTime, DateTimeKind.Utc)); UnitsProcessed += (long)entry.Size; } } SetDirectoryWriteTimes(); }
public static String docxParser(String filename) { //path to the systems temporary folder String tempFolderPath = Path.GetTempPath(); //set the path of the 7z.dll (it needs to be in the debug folder) SevenZipExtractor.SetLibraryPath("7z.dll"); SevenZipExtractor extractor = new SevenZipExtractor(filename); //create a filestream for the file we are going to extract FileStream f = new FileStream(tempFolderPath + "document.xml", FileMode.Create); //extract the document.xml extractor.ExtractFile("word\\document.xml", f); //get rid of the object because it is unmanaged extractor.Dispose(); //close the filestream f.Close(); //send document.xml that we extracted from the .docx to the xml parser String result = XMLParser.Parser.ParseXMLtoString(tempFolderPath + "document.xml"); //delete the extracted file from the temp folder File.Delete(tempFolderPath + "document.xml"); return result; }
public static byte[] ExtractBytes(byte[] data) { Inits.EnsureBinaries(); using (var inStream = new MemoryStream(data)) { using (var outStream = new MemoryStream()) { try { using (var extract = new SevenZipExtractor(inStream)) { extract.ExtractFile(0, outStream); return outStream.ToArray(); } } catch { try { return SevenZipExtractor.ExtractBytes(inStream.ToArray()); } catch { return null; } } } } }
public TickReader(FileInfo file) { Serializer = new PbTickSerializer(); Codec = new QuantBox.Data.Serializer.V2.PbTickCodec(); _stream = new MemoryStream(); _originalLength = (int)file.Length; // 加载文件,支持7z解压 var fileStream = file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite); { try { using (var zip = new SevenZipExtractor(fileStream)) { zip.ExtractFile(0, _stream); _stream.Seek(0, SeekOrigin.Begin); } } catch { _stream = fileStream; _stream.Seek(0, SeekOrigin.Begin); } } }
public int Decompress(PointCloudTile tile, byte[] compressedBuffer, int count, byte[] uncompressedBuffer) { MemoryStream uncompressedStream = new MemoryStream(uncompressedBuffer); MemoryStream compressedStream = new MemoryStream(compressedBuffer, 0, count, false); using (SevenZipExtractor extractor = new SevenZipExtractor(compressedStream)) { extractor.ExtractFile(0, uncompressedStream); } return (int)uncompressedStream.Position; }
public void TestRead() { var file = new FileInfo("TickDataV1_1"); using (var stream = new MemoryStream()) using (var fileStream = file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var zip = new SevenZipExtractor(fileStream)) { zip.ExtractFile(0, stream); stream.Seek(0, SeekOrigin.Begin); var serializer = new PbTickSerializer(); var codec = new PbTickCodec(); foreach (var tick in serializer.Read(stream)) { } } }
private ArchiveFileInfo GetArchiveFileInfo(SevenZibSharp.ArchiveFileInfo entry, SevenZibSharp.SevenZipExtractor archiveFile) { using (var entryStream = new MemoryStream()) { archiveFile.ExtractFile(entry.FileName, entryStream); var retVal = new ArchiveFileInfo { FileName = entry.FileName, Content = entryStream.ToArray() }; entryStream.Close(); return(retVal); } }
public void Extract(string archivePath, string filePath, string destFilePath) { using (var destFileStream = new FileStream(destFilePath, FileMode.Create, FileAccess.Write)) { this.SetLibraryPath(); var extractor = new SevenZipExtractor(archivePath); extractor.ExtractionFinished += this.ExtractionFinished; extractor.ExtractFile(filePath, destFileStream); destFileStream.Flush(); destFileStream.Close(); } }
private void ExtractFile( SevenZipExtractor extractor, ManifestFile file) { using (var destFileStream = new FileStream(file.InstallPath, FileMode.Create, FileAccess.Write)) { try { extractor.ExtractFile(file.File, destFileStream); } catch (Exception exception) { } destFileStream.Flush(); destFileStream.Close(); } }
public static byte[] DecompressBytes(byte[] data) { byte[] uncompressedbuffer = null; using (MemoryStream compressedbuffer = new MemoryStream(data)) { using (SevenZipExtractor extractor = new SevenZipExtractor(compressedbuffer)) { using (MemoryStream msout = new MemoryStream()) { extractor.ExtractFile(0, msout); uncompressedbuffer = msout.ToArray(); } } } return uncompressedbuffer; }
public static int extractArchive(string inFileName, string extractPath) { // extract input archive FileStream fileStream; SevenZipExtractor extractor = null; try { extractor = new SevenZipExtractor(File.OpenRead(inFileName)); foreach (var fileName in extractor.ArchiveFileNames) { // you of course can extract to a file stream instead of a memory stream if you want :) //var memoryStream = new MemoryStream(); //extractor.ExtractFile(fileName, memoryStream); // do what you want with your file here :) fileStream = File.Create(Path.Combine(extractPath, fileName)); extractor.ExtractFile(fileName, fileStream); int buffersize = 1024; byte[] buffer = new byte[buffersize]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffersize)) != 0) { fileStream.Write(buffer, 0, bytesRead); } // end while fileStream.Close(); } extractor.Dispose(); } catch (Exception ex) { Logger.Logwrite(ex.Message); Console.Error.WriteLine("Error: Could not open input archive: " + inFileName); Console.Error.WriteLine("\t" + ex.Message); } finally { } return 1; }
public Stream Extract(string archivePath, string filePath) { this.SetLibraryPath(); var extractor = new SevenZipExtractor(archivePath); extractor.ExtractionFinished += this.ExtractionFinished; var stream = new MemoryStream(); var matchingfile = extractor.ArchiveFileData.Where(x => x.FileName == filePath).FirstOrDefault(); extractor.ExtractFile(matchingfile.Index, stream); // reset stream position to the start stream.Position = 0; return stream; }
// Returns plain string from compressed and encoded input private static String myDecode(string input) { // Create a memory stream from the input: base64 --> bytes --> memStream Byte[] compBytes = Convert.FromBase64String(input); MemoryStream compStreamIn = new MemoryStream(compBytes); SevenZipExtractor.SetLibraryPath(@"C:\Temp\7za64.dll"); var SevenZipE = new SevenZip.SevenZipExtractor(compStreamIn, "Optional Password Field"); var OutputStream = new MemoryStream(); SevenZipE.ExtractFile(0, OutputStream); var OutputBase64 = Convert.ToBase64String(OutputStream.ToArray()); Byte[] OutputBytes = Convert.FromBase64String(OutputBase64); string output = Encoding.UTF8.GetString(OutputBytes); return(output); }
static byte[] ExtractFile(string archive, string file) { if (!archive.ToLower().EndsWith("sdz") && !archive.ToLower().EndsWith("sd7")) throw new ArgumentException("Invalid archive name"); var stream = new MemoryStream(); var format = archive.EndsWith("sdz") ? InArchiveFormat.Zip : InArchiveFormat.SevenZip; // extract the file synchronously var thread = new Thread(() => { using (var extractor = new SevenZipExtractor(File.OpenRead(archive), format)) { extractor.ExtractFile(file, stream, true); } }); thread.Start(); thread.Join(); stream.Position = 0; return stream.ToArray(); }
static void Main(string[] args) { var log = new StreamWriter(ConfigurationManager.AppSettings["output_file"]) { AutoFlush = true }; var re = new System.Text.RegularExpressions.Regex(@"\d{7,8}-[\dkK]"); Console.Write("Descomprimiendo el archivo {0}.7z... ", ConfigurationManager.AppSettings["path_file_contribuyentes"]); var ms = new MemoryStream(); SevenZip.SevenZipExtractor.SetLibraryPath("7z-x86.dll"); var sevenZip = new SevenZip.SevenZipExtractor(ConfigurationManager.AppSettings["path_file_contribuyentes"] + ".7z"); sevenZip.ExtractFile(ConfigurationManager.AppSettings["path_file_contribuyentes"] + ".csv", ms); Console.Write("Ok!\n\r"); Console.Write("Leyendo el archivo {0}.csv... ", ConfigurationManager.AppSettings["path_file_contribuyentes"]); var binaryContent = ms.GetBuffer(); var stringContent = System.Text.Encoding.GetEncoding("UTF-8").GetString(binaryContent); Console.Write("Ok!\n\r"); Console.Write("Procesando registros...\n\r"); var contribuyentes = stringContent.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); foreach (var contribuyente in contribuyentes) { var arr = contribuyente.Split(';'); if (re.IsMatch(arr[0])) { var rut = arr[0].Split('-')[0]; var dv = arr[0].Split('-')[1]; var resultado = GetDocumentosAutorizados(rut, dv); Console.WriteLine(resultado); log.WriteLine(resultado); } } Console.Write("\n\rPresione cualquier teclar para continuar...\n\r"); Console.ReadKey(); }
private static bool ExtractionBenchmark(string archiveFileName, Stream outStream, ref LibraryFeature?features, LibraryFeature testedFeature) { var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(GetResourceString(archiveFileName)); try { using (var extractor = new SevenZipExtractor(stream)) { extractor.ExtractFile(0, outStream); } } catch (Exception) { return(false); } features |= testedFeature; return(true); }
public static Book LoadBook(string path) { Book book; book = new Book() { Name = Path.GetFileName(path), FilePath = path, Pages = new List<Page>() }; SevenZipExtractor.SetLibraryPath(@"C:\Program Files (x86)\7-Zip\7z.dll"); using (var zip = new SevenZipExtractor(path)) { foreach (var file in zip.ArchiveFileData) { try { var s = new MemoryStream(); zip.ExtractFile(file.FileName, s); Image image = new Bitmap(s); var page = new Page(); page.Name = file.FileName; page.Display = image; book.Pages.Add(page); } catch (Exception e) { } } } book.Pages = book.Pages.OrderBy(p => p.Name).ToList(); return book; }
/// <summary> /// 解压字节数组 /// </summary> /// <param name="input"></param> /// <returns></returns> public static byte[] Decompress(byte[] input) { byte[] uncompressedbuffer = null; using (MemoryStream msin = new MemoryStream(input)) { msin.Position = 0; using (SevenZipExtractor extractor = new SevenZipExtractor(msin)) { using (MemoryStream msout = new MemoryStream()) { extractor.ExtractFile(0, msout); msout.Position = 0; uncompressedbuffer = new byte[msout.Length]; msout.Read(uncompressedbuffer, 0, uncompressedbuffer.Length); } } } return uncompressedbuffer; }
public List<QuantBox.Data.Serializer.V2.PbTickView> ReadOneFile(FileInfo file) { Stream _stream = new MemoryStream(); var fileStream = file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite); { try { using (var zip = new SevenZipExtractor(fileStream)) { zip.ExtractFile(0, _stream); _stream.Seek(0, SeekOrigin.Begin); } } catch(Exception ex) { _stream = fileStream; _stream.Seek(0, SeekOrigin.Begin); } } return Serializer.Read2View(_stream); }
public static bool ExtractFFmpeg(string zipPath, string extractPath) { try { if (NativeMethods.Is64Bit()) { SevenZipExtractor.SetLibraryPath(Path.Combine(Application.StartupPath, "7z-x64.dll")); } else { SevenZipExtractor.SetLibraryPath(Path.Combine(Application.StartupPath, "7z.dll")); } Helpers.CreateDirectoryIfNotExist(extractPath); using (SevenZipExtractor zip = new SevenZipExtractor(zipPath)) { Regex regex = new Regex(@"^ffmpeg-.+\\bin\\ffmpeg\.exe$", RegexOptions.Compiled | RegexOptions.CultureInvariant); foreach (ArchiveFileInfo item in zip.ArchiveFileData) { if (regex.IsMatch(item.FileName)) { using (FileStream fs = new FileStream(extractPath, FileMode.Create, FileAccess.Write, FileShare.None)) { zip.ExtractFile(item.Index, fs); return true; } } } } } catch (Exception e) { DebugHelper.WriteException(e); } return false; }
private void PlaySelected() { if (managedListView1.SelectedItems.Count != 1) { ManagedMessageBox.ShowErrorMessage(Program.ResourceManager.GetString("Message_PleaseSelectOneGameToPlay")); return; } string id = managedListView1.SelectedItems[0].Tag.ToString(); bool isArchive = false; MyNesDBEntryInfo entry = MyNesDB.GetEntry(id); string path = entry.Path; string tempFile = path; int aIndex = 0; if (path.StartsWith("(")) { isArchive = true; // Decode aIndex = GetFileIndexFromArchivePath(path); path = GetFilePathFromArchivePath(path); } if (isArchive) { // Extract the archive string tempFolder = Path.GetTempPath() + "\\MYNES\\"; Directory.CreateDirectory(tempFolder); // Extract it ! SevenZipExtractor extractor = new SevenZipExtractor(path); tempFile = tempFolder + extractor.ArchiveFileData[aIndex].FileName; Stream aStream = new FileStream(tempFile, FileMode.Create, FileAccess.Write); extractor.ExtractFile(aIndex, aStream); aStream.Close(); } if (File.Exists(tempFile)) { if (NesEmu.EmulationON) UpdatePlayStatus(); // Play it ! currentPlayedGameIndex = managedListView1.Items.IndexOf(managedListView1.SelectedItems[0]); currentPlayedGameId = id; Program.FormMain.OpenRom(tempFile); Program.FormMain.Activate(); if (NesEmu.EmulationON) { isPlayingGame = true; playTime = 0; timer_play.Start(); if (Program.Settings.LauncherAutoMinimize) this.WindowState = FormWindowState.Minimized; Program.FormMain.AddRecent(path); } } else { ManagedMessageBox.ShowErrorMessage(Program.ResourceManager.GetString("Message_GameFileNotExistOrNoFileAssignedToThisGameYet")); } }
private void ShowGameInfo(object sender, EventArgs e) { if (managedListView1.SelectedItems.Count != 1) { ManagedMessageBox.ShowErrorMessage(Program.ResourceManager.GetString("Message_PleaseSelectOneGameToShowInfoOf")); return; } string id = managedListView1.SelectedItems[0].Tag.ToString(); bool isArchive = false; MyNesDBEntryInfo entry = MyNesDB.GetEntry(id); string path = entry.Path; string tempFile = path; int aIndex = 0; if (path.StartsWith("(")) { isArchive = true; // Decode string[] pathCodes = path.Split(new char[] { '(', ')' }); int.TryParse(pathCodes[1], out aIndex); path = pathCodes[2]; } if (isArchive) { // Extract the archive string tempFolder = Path.GetTempPath() + "\\MYNES\\"; Directory.CreateDirectory(tempFolder); // Extract it ! SevenZipExtractor extractor = new SevenZipExtractor(path); tempFile = tempFolder + extractor.ArchiveFileData[aIndex].FileName; Stream aStream = new FileStream(tempFile, FileMode.Create, FileAccess.Write); extractor.ExtractFile(aIndex, aStream); aStream.Close(); } if (File.Exists(tempFile)) { if (NesEmu.EmulationON) NesEmu.EmulationPaused = true; FormRomInfo form = new FormRomInfo(tempFile); form.ShowDialog(this); if (NesEmu.EmulationON) NesEmu.EmulationPaused = false; } else { ManagedMessageBox.ShowErrorMessage(Program.ResourceManager.GetString("Message_GameFileNotExistOrNoFileAssignedToThisGameYet")); } }
private Stream ExtractEntry(SevenZipExtractor zip, ArchiveFileInfo? entry) { if (entry != null && zip != null) { var memoryStream = new MemoryStream(); ArchiveFileInfo entryValue = entry.GetValueOrDefault(); if (entryValue != null) { zip.ExtractFile(entryValue.Index, memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); return memoryStream; } } return null; }
public void ExtractFileDiskTest(){ 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.FileExists += (o, e) =>{ TestContext.WriteLine("Warning: file \"" + e.FileName + "\" already exists."); //e.Overwrite = false; }; tmp.ExtractionFinished += (s, e) => { TestContext.WriteLine("Finished!"); }; var rand = new Random(); tmp.ExtractFile(rand.Next((int) tmp.FilesCount), File.Create(createTempFileName())); } }
private static bool ExtractionBenchmark(string archiveFileName, Stream outStream, ref LibraryFeature? features, LibraryFeature testedFeature) { var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream( GetResourceString(archiveFileName)); try { using (var extr = new SevenZipExtractor(stream)) { extr.ExtractFile(0, outStream); } } catch (Exception) { return false; } features |= testedFeature; return true; }
private static DataTable LoadCAMTFile(string sourceFile) { Hashtable picfiles = new Hashtable(); XmlDocument xml = new XmlDocument(); using (SevenZip.SevenZipExtractor extractorgz = new SevenZip.SevenZipExtractor(sourceFile)) { byte[] gz = null; MemoryStream msgz = new MemoryStream(); extractorgz.ExtractFile(0, msgz); msgz.Position = 0; using (SevenZip.SevenZipExtractor extractortar = new SevenZipExtractor(msgz)) { foreach (string fn in extractortar.ArchiveFileNames) { MemoryStream mstar = new MemoryStream(); extractortar.ExtractFile(fn, mstar); mstar.Position = 0; if (fn.ToUpper().EndsWith(".XML")) { xml = new XmlDocument(); xml.Load(mstar); } else { byte[] tiff = mstar.ToArray(); picfiles.Add(fn, tiff); } mstar.Close(); Console.WriteLine(fn); } } msgz.Close(); } // Document class created using XSD.EXE from Microsoft SDKs to generate class from XSD file! // https://docs.microsoft.com/en-us/dotnet/standard/serialization/xml-schema-def-tool-gen XmlSerializer ser = new XmlSerializer(typeof(Document)); XmlReader xmlReader = new XmlNodeReader(xml); Document myDoc = ser.Deserialize(xmlReader) as Document; DataTable dt = new DataTable(); dt.Columns.Add(new DataColumn("Name", typeof(string))); dt.Columns.Add(new DataColumn("Image", typeof(byte[]))); dt.Columns.Add(new DataColumn("AcctIdIBAN", typeof(string))); dt.Columns.Add(new DataColumn("AcctOwnrNm", typeof(string))); dt.Columns.Add(new DataColumn("NtryAmt", typeof(string))); foreach (var stmt in myDoc.BkToCstmrStmt.Stmt) { foreach (var ntry in stmt.Ntry) { foreach (var ntrydtls in ntry.NtryDtls) { foreach (var txdtls in ntrydtls.TxDtls) { DataRow dr = dt.NewRow(); string AMT = txdtls.Amt.Value.ToString(); if (txdtls.Refs != null && txdtls.Refs.Prtry != null) { foreach (var prtry in txdtls.Refs.Prtry) { if (prtry.Ref != null) { foreach (string k in picfiles.Keys) { if (k.Contains(prtry.Ref)) { dr["Name"] = k; dr["Image"] = picfiles[k]; } } } } } dr["AcctIdIBAN"] = (txdtls.RltdPties == null || txdtls.RltdPties.DbtrAcct == null) ? string.Empty : txdtls.RltdPties.DbtrAcct.Id.Item; dr["AcctOwnrNm"] = (txdtls.RltdPties == null || txdtls.RltdPties.Dbtr == null) ? string.Empty : txdtls.RltdPties.Dbtr.Nm; dr["NtryAmt"] = AMT; if (!string.IsNullOrWhiteSpace(dr["Name"] + string.Empty)) { dt.Rows.Add(dr); } } } } } return(dt); }
/// <summary> /// Gets a <see cref="SevenZipExtractor"/> for the given path. /// </summary> /// <remarks> /// This builds a <see cref="SevenZipExtractor"/> for the given path. The path can /// be to a nested archive (an archive in another archive). /// </remarks> /// <param name="p_strPath">The path to the archive for which to get a <see cref="SevenZipExtractor"/>.</param> /// <param name="p_booThreadSafe">Indicates if the returned extractor need to be thread safe.</param> /// <returns>A <see cref="SevenZipExtractor"/> for the given path if the extractor doesn't need to be /// thread safe; a <see cref="ThreadSafeSevenZipExtractor"/> otherwise.</returns> private static object GetExtractor(string p_strPath, bool p_booThreadSafe) { if (p_strPath.StartsWith(Archive.ARCHIVE_PREFIX)) { Stack<KeyValuePair<string, string>> stkFiles = new Stack<KeyValuePair<string, string>>(); string strPath = p_strPath; while (strPath.StartsWith(Archive.ARCHIVE_PREFIX)) { stkFiles.Push(Archive.ParseArchivePath(strPath)); strPath = stkFiles.Peek().Key; } Stack<SevenZipExtractor> stkExtractors = new Stack<SevenZipExtractor>(); try { KeyValuePair<string, string> kvpArchive = stkFiles.Pop(); SevenZipExtractor szeArchive = new SevenZipExtractor(kvpArchive.Key); stkExtractors.Push(szeArchive); for (; stkFiles.Count > 0; kvpArchive = stkFiles.Pop()) { MemoryStream msmArchive = new MemoryStream(); szeArchive.ExtractFile(kvpArchive.Value, msmArchive); msmArchive.Position = 0; szeArchive = new SevenZipExtractor(msmArchive); stkExtractors.Push(szeArchive); } MemoryStream msmFile = new MemoryStream(); szeArchive.ExtractFile(kvpArchive.Value, msmFile); msmFile.Position = 0; if (p_booThreadSafe) return new ThreadSafeSevenZipExtractor(msmFile); return new SevenZipExtractor(msmFile); } finally { while (stkExtractors.Count > 0) stkExtractors.Pop().Dispose(); } } else { if (p_booThreadSafe) return new ThreadSafeSevenZipExtractor(p_strPath); return new SevenZipExtractor(p_strPath); } }
/// <summary> /// Loads the list of data files in the mod. /// </summary> /// <param name="p_szeOmod">The extractor from which to read the file list.</param> protected void ExtractDataFileList(SevenZipExtractor p_szeOmod) { if (!p_szeOmod.ArchiveFileNames.Contains("data.crc")) return; using (Stream stmDataFileList = new MemoryStream()) { p_szeOmod.ExtractFile("data.crc", stmDataFileList); stmDataFileList.Position = 0; using (BinaryReader brdDataFileList = new BinaryReader(stmDataFileList)) { while (brdDataFileList.PeekChar() != -1) DataFileList.Add(new FileInfo(brdDataFileList.ReadString(), brdDataFileList.ReadUInt32(), brdDataFileList.ReadInt64())); } } }
/// <summary> /// Starts a read-only transaction. /// </summary> /// <remarks> /// This puts the OMod into read-only mode. /// /// Read-only mode can greatly increase the speed at which multiple file are extracted. /// </remarks> public void BeginReadOnlyTransaction(FileUtil p_futFileUtil) { if (!IsPacked) { m_arcFile.ReadOnlyInitProgressUpdated += new CancelProgressEventHandler(ArchiveFile_ReadOnlyInitProgressUpdated); m_arcFile.BeginReadOnlyTransaction(p_futFileUtil); return; } m_strReadOnlyTempDirectory = p_futFileUtil.CreateTempDirectory(); string[] strFileStreamNames = { "plugins", "data" }; List<FileInfo> lstFiles = null; byte[] bteUncompressedFileData = null; m_intReadOnlyInitFileBlockExtractionCurrentStage = 0; m_fltReadOnlyInitCurrentBaseProgress = 0; foreach (string strFileStreamName in strFileStreamNames) { //extract the compressed file block... using (Stream stmCompressedFiles = new MemoryStream()) { using (SevenZipExtractor szeOmod = new SevenZipExtractor(m_strFilePath)) { if (!szeOmod.ArchiveFileNames.Contains(strFileStreamName)) continue; m_intReadOnlyInitFileBlockExtractionCurrentStage++; szeOmod.ExtractFile(strFileStreamName, stmCompressedFiles); switch (strFileStreamName) { case "plugins": lstFiles = PluginList; break; case "data": lstFiles = DataFileList; break; default: throw new Exception("Unexpected value for file stream name: " + strFileStreamName); } } stmCompressedFiles.Position = 0; Int64 intTotalLength = lstFiles.Sum(x => x.Length); bteUncompressedFileData = new byte[intTotalLength]; switch (CompressionType) { case InArchiveFormat.SevenZip: byte[] bteProperties = new byte[5]; stmCompressedFiles.Read(bteProperties, 0, 5); Decoder dcrDecoder = new Decoder(); dcrDecoder.SetDecoderProperties(bteProperties); DecoderProgressWatcher dpwWatcher = new DecoderProgressWatcher(stmCompressedFiles.Length); dpwWatcher.ProgressUpdated += new EventHandler<EventArgs<int>>(dpwWatcher_ProgressUpdated); using (Stream stmUncompressedFiles = new MemoryStream(bteUncompressedFileData)) dcrDecoder.Code(stmCompressedFiles, stmUncompressedFiles, stmCompressedFiles.Length - stmCompressedFiles.Position, intTotalLength, dpwWatcher); break; case InArchiveFormat.Zip: using (SevenZipExtractor szeZip = new SevenZipExtractor(stmCompressedFiles)) { szeZip.Extracting += new EventHandler<ProgressEventArgs>(szeZip_Extracting); using (Stream stmFile = new MemoryStream(bteUncompressedFileData)) { szeZip.ExtractFile(0, stmFile); } } break; default: throw new Exception("Cannot get files: unsupported compression type: " + CompressionType.ToString()); } } float fltFileStreamPercentBlockSize = FILE_BLOCK_EXTRACTION_PROGRESS_BLOCK_SIZE / m_intReadOnlyInitFileBlockExtractionStages; float fltFileWritingPercentBlockSize = FILE_WRITE_PROGRESS_BLOCK_SIZE / m_intReadOnlyInitFileBlockExtractionStages; m_fltReadOnlyInitCurrentBaseProgress += fltFileStreamPercentBlockSize; //...then write each file to the temporary location Int64 intFileStart = 0; byte[] bteFile = null; Crc32 crcChecksum = new Crc32(); for (Int32 i = 0; i < lstFiles.Count; i++) { FileInfo ofiFile = lstFiles[i]; bteFile = new byte[ofiFile.Length]; Array.Copy(bteUncompressedFileData, intFileStart, bteFile, 0, ofiFile.Length); intFileStart += ofiFile.Length; FileUtil.WriteAllBytes(Path.Combine(m_strReadOnlyTempDirectory, ofiFile.Name), bteFile); crcChecksum.Initialize(); crcChecksum.ComputeHash(bteFile); if (crcChecksum.CrcValue != ofiFile.CRC) throw new Exception(String.Format("Unable to extract {0}: checksums did not match. OMod is corrupt.", ofiFile.Name)); UpdateReadOnlyInitProgress(m_fltReadOnlyInitCurrentBaseProgress, fltFileWritingPercentBlockSize, i / lstFiles.Count); } m_fltReadOnlyInitCurrentBaseProgress += fltFileWritingPercentBlockSize; } m_fltReadOnlyInitCurrentBaseProgress = FILE_BLOCK_EXTRACTION_PROGRESS_BLOCK_SIZE + FILE_WRITE_PROGRESS_BLOCK_SIZE; Int32 intRemainingSteps = (m_booHasInstallScript ? 1 : 0) + (m_booHasReadme ? 1 : 0) + (m_booHasScreenshot ? 1 : 0); Int32 intStepCounter = 1; if (m_booHasScreenshot) { File.WriteAllBytes(Path.Combine(m_strReadOnlyTempDirectory, ScreenshotPath), GetSpecialFile(ScreenshotPath)); UpdateReadOnlyInitProgress(m_fltReadOnlyInitCurrentBaseProgress, 1f - m_fltReadOnlyInitCurrentBaseProgress, 1f / intRemainingSteps * intStepCounter++); } if (m_booHasInstallScript) { File.WriteAllBytes(Path.Combine(m_strReadOnlyTempDirectory, "script"), GetSpecialFile("script")); UpdateReadOnlyInitProgress(m_fltReadOnlyInitCurrentBaseProgress, 1f - m_fltReadOnlyInitCurrentBaseProgress, 1f / intRemainingSteps * intStepCounter++); } if (m_booHasReadme) { File.WriteAllBytes(Path.Combine(m_strReadOnlyTempDirectory, "readme"), GetSpecialFile("readme")); UpdateReadOnlyInitProgress(m_fltReadOnlyInitCurrentBaseProgress, 1f - m_fltReadOnlyInitCurrentBaseProgress, 1f / intRemainingSteps * intStepCounter); } }
/// <summary> /// Loads the mod metadata from the config file. /// </summary> /// <param name="p_szeOmod">The extractor from which to read the config file.</param> protected void ExtractConfig(SevenZipExtractor p_szeOmod) { using (MemoryStream stmConfig = new MemoryStream()) { p_szeOmod.ExtractFile("config", stmConfig); stmConfig.Position = 0; LoadInfo(stmConfig.GetBuffer()); } }
/// <summary> /// Initializes an OMod in packed format. /// </summary> /// <param name="p_stgScriptTypeRegistry">The registry of supported script types.</param> private void InitializePackedOmod(IScriptTypeRegistry p_stgScriptTypeRegistry) { using (SevenZipExtractor szeOmod = new SevenZipExtractor(m_strFilePath)) { ExtractConfig(szeOmod); ExtractPluginList(szeOmod); ExtractDataFileList(szeOmod); if (szeOmod.ArchiveFileNames.Contains("plugins.crc")) m_intReadOnlyInitFileBlockExtractionStages++; if (szeOmod.ArchiveFileNames.Contains("data.crc")) m_intReadOnlyInitFileBlockExtractionStages++; //check for script m_booHasInstallScript = false; foreach (IScriptType stpScript in p_stgScriptTypeRegistry.Types) { foreach (string strScriptName in stpScript.FileNames) { if (szeOmod.ArchiveFileNames.Contains(strScriptName)) { using (MemoryStream stmScript = new MemoryStream()) { szeOmod.ExtractFile(strScriptName, stmScript); string strCode = System.Text.Encoding.Default.GetString(stmScript.ToArray()); if (stpScript.ValidateScript(stpScript.LoadScript(strCode))) { m_booHasInstallScript = true; m_stpInstallScriptType = stpScript; break; } } } } if (m_booHasInstallScript) break; } //check for readme m_booHasReadme = szeOmod.ArchiveFileNames.Contains("readme"); //check for screenshot m_booHasScreenshot = szeOmod.ArchiveFileNames.Contains("image"); } }
/// <summary> /// Retrieves the specified file from the OMod. /// </summary> /// <param name="p_strFile">The file to retrieve.</param> /// <returns>The requested file data.</returns> /// <exception cref="FileNotFoundException">Thrown if the specified file /// is not in the OMod.</exception> public byte[] GetFile(string p_strFile) { if (!ContainsFile(p_strFile)) throw new FileNotFoundException("File doesn't exist in OMod", p_strFile); if (!IsPacked) { if ((m_arcCacheFile != null) && m_arcCacheFile.ContainsFile(GetRealPath(p_strFile))) return m_arcCacheFile.GetFileContents(GetRealPath(p_strFile)); return m_arcFile.GetFileContents(GetRealPath(p_strFile)); } if (!String.IsNullOrEmpty(m_strReadOnlyTempDirectory)) return File.ReadAllBytes(Path.Combine(m_strReadOnlyTempDirectory, p_strFile)); List<FileInfo> lstFiles = null; byte[] bteFileBlock = null; using (Stream stmDataFiles = new MemoryStream()) { using (SevenZipExtractor szeOmod = new SevenZipExtractor(m_strFilePath)) { if (Path.GetExtension(p_strFile).Equals(".esm", StringComparison.OrdinalIgnoreCase) || Path.GetExtension(p_strFile).Equals(".esp", StringComparison.OrdinalIgnoreCase)) { szeOmod.ExtractFile("plugins", stmDataFiles); lstFiles = PluginList; } else { szeOmod.ExtractFile("data", stmDataFiles); lstFiles = DataFileList; } } stmDataFiles.Position = 0; Int64 intTotalLength = lstFiles.Sum(x => x.Length); bteFileBlock = new byte[intTotalLength]; switch (CompressionType) { case InArchiveFormat.SevenZip: byte[] bteProperties = new byte[5]; stmDataFiles.Read(bteProperties, 0, 5); Decoder dcrDecoder = new Decoder(); dcrDecoder.SetDecoderProperties(bteProperties); using (Stream stmFile = new MemoryStream(bteFileBlock)) dcrDecoder.Code(stmDataFiles, stmFile, stmDataFiles.Length - stmDataFiles.Position, intTotalLength, null); break; case InArchiveFormat.Zip: using (SevenZipExtractor szeZip = new SevenZipExtractor(stmDataFiles)) { using (Stream stmFile = new MemoryStream(bteFileBlock)) { szeZip.ExtractFile(0, stmFile); } } break; default: throw new Exception("Cannot get file: unsupported compression type: " + CompressionType.ToString()); } } Int64 intFileStart = 0; byte[] bteFile = null; foreach (FileInfo ofiFile in lstFiles) { if (!ofiFile.Name.Equals(p_strFile, StringComparison.OrdinalIgnoreCase)) intFileStart += ofiFile.Length; else { bteFile = new byte[ofiFile.Length]; Array.Copy(bteFileBlock, intFileStart, bteFile, 0, ofiFile.Length); break; } } return bteFile; }
/// <summary> /// Retrieves the specified file from the OMod. /// </summary> /// <param name="p_strFile">The file to retrieve.</param> /// <returns>The requested file data.</returns> /// <exception cref="FileNotFoundException">Thrown if the specified file /// is not in the OMod.</exception> protected byte[] GetSpecialFile(string p_strFile) { bool booFound = false; bool booIsBinary = false; switch (p_strFile) { case "config": booFound = true; booIsBinary = true; break; case "image": case "screenshot": booFound = m_booHasScreenshot; booIsBinary = true; break; case "readme": booFound = m_booHasReadme; break; case "script": if (!IsPacked) p_strFile = "script.txt"; booFound = m_booHasInstallScript; break; } if (!booFound) throw new FileNotFoundException("Special File doesn't exist in OMod", p_strFile); byte[] bteFile = null; if (!IsPacked) { string strPath = Path.Combine(CONVERSION_FOLDER, p_strFile); if ((m_arcCacheFile != null) && m_arcCacheFile.ContainsFile(GetRealPath(strPath))) return m_arcCacheFile.GetFileContents(GetRealPath(strPath)); bteFile = m_arcFile.GetFileContents(GetRealPath(strPath)); if (!booIsBinary) bteFile = System.Text.Encoding.Default.GetBytes(TextUtil.ByteToString(bteFile).Trim('\0')); } else { using (MemoryStream msmFile = new MemoryStream()) { using (SevenZipExtractor szeOmod = new SevenZipExtractor(m_strFilePath)) szeOmod.ExtractFile(p_strFile, msmFile); if (booIsBinary) bteFile = msmFile.GetBuffer(); else { using (BinaryReader brdReader = new BinaryReader(msmFile)) { msmFile.Position = 0; bteFile = System.Text.Encoding.Default.GetBytes(brdReader.ReadString().Trim('\0')); brdReader.Close(); } } msmFile.Close(); } } return bteFile; }
private string Run(int revision, string additionalFilePath, bool autoStartChecked) { string filename = string.Format("bootcd-{0}-dbg", revision); string filename7z = filename + ".7z"; string filenameIso = filename + ".iso"; if (!File.Exists(filenameIso)) { string filename7zTemp = filename7z + ".temp"; string filenameIsoTemp = filenameIso + ".temp"; if (!File.Exists(filename7z)) { File.Delete(filename7zTemp); WebClient wc = new WebClient(); try { wc.DownloadFile(revToUrl[revision], filename7zTemp); } catch (WebException) { return "File download failed:\n '" + revToUrl[revision] + "'"; } File.Move(filename7zTemp, filename7z); } File.Delete(filenameIsoTemp); FileStream isotmpfs = File.Create(filenameIsoTemp); FileStream szfs = File.Open(filename7z, FileMode.Open, FileAccess.Read); SevenZipExtractor sze = new SevenZipExtractor(szfs); sze.ExtractFile(filenameIso, isotmpfs); isotmpfs.Close(); szfs.Close(); File.Move(filenameIsoTemp, filenameIso); File.Delete(filename7z); } string vmName = string.Format("ReactOS_r{0}", revision); string diskName = Environment.CurrentDirectory + "\\" + vmName + "\\" + vmName + ".vdi"; if (File.Exists(diskName)) { FileStream fs = null; try { fs = File.Open(diskName, FileMode.Open, FileAccess.Read, FileShare.None); } catch (IOException) { return "Virtual machine '" + vmName + "' is already running"; } finally { if (fs != null) fs.Close(); } } string filenameIsoUnatt = filename + "_unatt.iso"; string filenameIsoUnattTemp = filenameIsoUnatt + ".temp"; File.Delete(filenameIsoUnattTemp); File.Delete(filenameIsoUnatt); FileStream isofs = File.Open(filenameIso, FileMode.Open, FileAccess.Read); CDReader cdr = new CDReader(isofs, true); CDBuilder cdb = new CDBuilder(); cdb.VolumeIdentifier = cdr.VolumeLabel; CloneCdDirectory("", cdr, cdb); if (!File.Exists("unattend.inf")) File.WriteAllText("unattend.inf", RosRegTest.Resources.unattend, Encoding.ASCII); string additionalFileName = null; if (additionalFilePath != null) additionalFileName = Path.GetFileName(additionalFilePath); string unattText = File.ReadAllText("unattend.inf", Encoding.ASCII); if (autoStartChecked && (additionalFileName != null)) unattText = unattText + "[GuiRunOnce]\n" + "cmd.exe /c start d:\\" + additionalFileName + "\n\n"; cdb.AddFile("reactos\\unattend.inf", Encoding.ASCII.GetBytes(unattText)); if (additionalFileName != null) cdb.AddFile(additionalFileName, additionalFilePath); Stream bootImgStr = cdr.OpenBootImage(); cdb.SetBootImage(bootImgStr, cdr.BootEmulation, cdr.BootLoadSegment); bootImgStr.Close(); cdb.Build(filenameIsoUnattTemp); isofs.Close(); File.Move(filenameIsoUnattTemp, filenameIsoUnatt); string fullIsoName = Environment.CurrentDirectory + "\\" + filenameIsoUnatt; string deleteVmCmd = string.Format("unregistervm --name {0}", vmName); string createVmCmd = string.Format( "createvm --name {0} --basefolder {1} --ostype WindowsXP --register", vmName, Environment.CurrentDirectory); string modifyVmCmd = string.Format("modifyvm {0} --memory 256 --vram 16 --nictype1 Am79C973 --audio none --boot1 disk --boot2 dvd", vmName); string storageCtlCmd = string.Format("storagectl {0} --name \"IDE Controller\" --add ide", vmName); string createMediumCmd = string.Format("createmedium disk --filename {0} --size 2048", diskName); string storageAttachCmd1 = string.Format("storageattach {0} --port 0 --device 0 --storagectl \"IDE Controller\" --type hdd --medium {1}", vmName, diskName); string storageAttachCmd2 = string.Format("storageattach {0} --port 1 --device 0 --storagectl \"IDE Controller\" --type dvddrive --medium {1}", vmName, fullIsoName); string startCmd = string.Format("startvm {0}", vmName); Exec(vboxManagePath, deleteVmCmd); Exec(vboxManagePath, createVmCmd); Exec(vboxManagePath, modifyVmCmd); Exec(vboxManagePath, storageCtlCmd); Exec(vboxManagePath, createMediumCmd); Exec(vboxManagePath, storageAttachCmd1); Exec(vboxManagePath, storageAttachCmd2); Exec(vboxManagePath, startCmd); return null; }
//where's my async? public bool Install(out string err) { err = null; using (var wc = new WebClient()) { Log.File(Localization.RequestingNvsePage, Paths.NvseLink); string dlLink; using (var resStream = wc.OpenRead(Paths.NvseLink)) { if (!Util.PatternSearch(resStream, Paths.NvseSearchPattern, out dlLink)) { err = Localization.FailedDownloadNvse; return false; } } Log.File(Localization.ParsedNvseLink, dlLink.Truncate(100)); var archiveName = Path.GetFileName(dlLink); var tmpPath = Path.Combine(Path.GetTempPath(), archiveName); wc.DownloadFile(dlLink, tmpPath); using (var lzExtract = new SevenZipExtractor(tmpPath)) { if (!lzExtract.Check()) { err = string.Format(Localization.Invalid7zArchive, archiveName); return false; } var wantedFiles = (from file in lzExtract.ArchiveFileNames let filename = Path.GetFileName(file) let ext = Path.GetExtension(filename).ToUpperInvariant() where ext == ".EXE" || ext == ".DLL" select new { file, filename }).ToArray(); foreach (var a in wantedFiles) { var savePath = Path.Combine(_fnvPath, a.filename); Log.File(Localization.Extracting, a.filename); using (var fsStream = File.OpenWrite(savePath)) { try { lzExtract.ExtractFile(a.file, fsStream); } catch { err = Localization.FailedExtractNvse; throw; } } } } } Log.Dual(Localization.NvseInstallSuccessful); return true; }
private Tuple<Stream, string, double> ReadToStream(string pathChosen) { int cnt = 0; SevenZipExtractor extractor; try { extractor = new SevenZipExtractor(pathChosen); cnt = extractor.ArchiveFileData.Count; } catch (SevenZipException ex) { MessageBox.Show(ex.ToString()); return DirectReadToStream(pathChosen); } catch (ArgumentException ex) { return DirectReadToStream(pathChosen); } catch (Exception ex) { return DirectReadToStream(pathChosen); } List<string> listFileNames = new List<string>(); for (int i = 0; i < cnt; i++) { listFileNames.Add(extractor.ArchiveFileNames[i]); } string fileName = GetFileChosen(listFileNames); MemoryStream stream = new MemoryStream(); try { extractor.ExtractFile(fileName, stream); stream.Position = 0; } catch (Exception ex) { MessageBox.Show(ex.Message); return null; } double fileLength = stream.Length; Tuple<Stream, string, double> tuple = new Tuple<Stream, string, double>(stream, fileName, fileLength); return tuple; }