protected override IReader CreateReaderForSolidExtraction() { Stream stream = Enumerable.Single <ZipVolume>(base.Volumes).Stream; stream.Position = 0L; return(ZipReader.Open(stream, null, Options.KeepStreamsOpen)); }
// find the content type of a part in the package private string findContentType(ZipReader reader, string target) { // get extension without leading '.' string extension = Path.GetExtension(target).Substring(1); Stream contentTypes = reader.GetEntry(OOX_CONTENT_TYPE_FILE); XmlReader r = XmlReader.Create(contentTypes); bool overrided = false; string contentType = null; while (r.Read()) { if (r.NodeType == XmlNodeType.Element) { if (r.LocalName.Equals("Default") && r.GetAttribute("Extension").Equals(extension) && !overrided) { contentType = r.GetAttribute("ContentType"); } else if (r.LocalName.Equals("Override") && r.GetAttribute("PartName").Equals(target)) { overrided = true; contentType = r.GetAttribute("ContentType"); } } } if (contentType == null) { throw new ValidationException("Content type not found for " + target); } return(contentType); }
/// <summary>Unpacks to file.</summary> /// <param name="args">The arguments.</param> /// <param name="file">The file.</param> private static void UnpackToFile(UploadArgs args, HttpPostedFile file) { Assert.ArgumentNotNull((object)args, "args"); Assert.ArgumentNotNull((object)file, "file"); string filename = FileUtil.MapPath(TempFolder.GetFilename("temp.zip")); file.SaveAs(filename); using (ZipReader zipReader = new ZipReader(filename)) { foreach (ZipEntry entry in zipReader.Entries) { string str = FileUtil.MakePath(args.Folder, entry.Name, '\\'); if (entry.IsDirectory) { Directory.CreateDirectory(str); } else { if (!args.Overwrite) { str = FileUtil.GetUniqueFilename(str); } Directory.CreateDirectory(Path.GetDirectoryName(str)); lock (FileUtil.GetFileLock(str)) FileUtil.CreateFile(str, entry.GetStream(), true); } } } }
public List <LogicComponent> Parse(FileInfo logicLibrary) { var logicComponents = new List <LogicComponent>(); using (var inputStream = logicLibrary.OpenRead()) using (var archive = ZipReader.Open(inputStream)) { try { while (archive.MoveToNextEntry()) { var entry = archive.Entry; if (entry.Key.EndsWith(".drl") || entry.Key.EndsWith(".drt")) { using (var output = new MemoryStream()) { archive.WriteEntryTo(output); var byteArray = output.ToArray(); var text = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length); logicComponents.Add(ParseDroolsFile(text)); } } } } catch (EndOfStreamException) { // Java JAR files are their own ZIP variant and we always get an exception if we try to parse it } } return(logicComponents); }
private static PackageProject ExtractPackageProject(string fileName) { PackageProject packageProject = null; using (var packageReader = new ZipReader(fileName)) { var packageEntry = packageReader.GetEntry("package.zip"); using (var memoryStream = new MemoryStream()) { StreamUtils.CopyStream(packageEntry.GetStream(), memoryStream, 0x4000); memoryStream.Seek(0, SeekOrigin.Begin); using (var reader = new ZipReader(memoryStream)) { foreach (var entry in reader.Entries) { if (!entry.Name.Is(Constants.ProjectKey)) { continue; } packageProject = IOUtils.LoadSolution(StreamUtil.LoadString(entry.GetStream())); break; } } } } return(packageProject); }
protected override IReader CreateReaderForSolidExtraction() { var stream = Volumes.Single().Stream; stream.Position = 0; return(ZipReader.Open(stream)); }
public static bool unZip(this string zipFile, string targetDir) { "UnZip Files will be created in folder: {0}".debug(targetDir); try { using (var file = File.OpenRead(zipFile)) { using (var reader = ZipReader.Open(file, null, Options.None)) while (reader.MoveToNextEntry()) { if (!reader.Entry.IsDirectory) { "writing file '{0}'".info(reader.Entry.FilePath); reader.WriteEntryToDirectory(targetDir, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite); } } file.Close(); } return(true); } catch (Exception ex) { "[zipFile]: {0}".error(ex.Message); return(false); } }
public void Zip_LZMA_WinzipAES_Read() { Assert.Throws <NotSupportedException>(() => { ResetScratch(); using ( Stream stream = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "Zip.lzma.winzipaes.zip"))) using (var reader = ZipReader.Open(stream, "test")) { while (reader.MoveToNextEntry()) { if (!reader.Entry.IsDirectory) { Assert.Equal(reader.Entry.CompressionType, CompressionType.Unknown); reader.WriteEntryToDirectory(SCRATCH_FILES_PATH, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite); } } } VerifyFiles(); }); }
public Tuple <long, long> ReadForwardOnly(string filename) { long count = 0; long size = 0; Common.Zip.ZipEntry prev = null; using (var fs = File.OpenRead(filename)) using (var rd = ZipReader.Open(fs, new ReaderOptions() { LookForHeader = false })) { while (rd.MoveToNextEntry()) { using (rd.OpenEntryStream()) { } count++; if (prev != null) { size += prev.Size; } prev = rd.Entry; } } if (prev != null) { size += prev.Size; } return(new Tuple <long, long>(count, size)); }
public void Run() { reader = new ZipReader(); reader.SelectZipEntry = SelectZipEntry_Classic; reader.ProcessZipEntry = ProcessZipEntry_Classic; string texDir = Path.Combine(Program.AppDirectory, "texpacks"); string path = Path.Combine(texDir, "default.zip"); ExtractExisting(path); using (Stream dst = new FileStream(path, FileMode.Create, FileAccess.Write)) { writer = new ZipWriter(dst); writer.entries = new ZipEntry[100]; for (int i = 0; i < entries.Count; i++) { writer.WriteZipEntry(entries[i], datas[i]); } ExtractClassic(); ExtractModern(); if (pngGuiPatch != null) { using (Bitmap gui = Platform.ReadBmp32Bpp(drawer, pngGuiPatch)) writer.WriteNewImage(gui, "gui.png"); } if (patchedTerrain) { writer.WriteNewImage(terrainBmp, "terrain.png"); } writer.WriteCentralDirectoryRecords(); } }
public static void Test_ViewCompressFile_01(string file) { //System.IO.Compression.ZipFile Trace.WriteLine("view compress file \"{0}\"", file); using (Stream stream = zFile.OpenRead(file)) { var reader = ReaderFactory.Open(stream); Trace.WriteLine("reader {0}", reader); Trace.WriteLine(" ArchiveType : {0}", reader.ArchiveType); ZipReader zipReader = reader as ZipReader; if (zipReader != null) { Trace.WriteLine(" ArchiveType : {0}", zipReader.ArchiveType); } while (reader.MoveToNextEntry()) { Trace.WriteLine(" FilePath : \"{0}\"", reader.Entry.FilePath); Trace.WriteLine(" ArchivedTime : {0}", reader.Entry.ArchivedTime); Trace.WriteLine(" CompressedSize : {0}", reader.Entry.CompressedSize); Trace.WriteLine(" CompressionType : {0}", reader.Entry.CompressionType); Trace.WriteLine(" CreatedTime : {0}", reader.Entry.CreatedTime); Trace.WriteLine(" IsDirectory : {0}", reader.Entry.IsDirectory); Trace.WriteLine(" IsEncrypted : {0}", reader.Entry.IsEncrypted); Trace.WriteLine(" Size : {0}", reader.Entry.Size); } } }
public LibIOZipExtractor(ILogger logger, FileInfo inputFile, Dictionary <string, object> options) : base(logger, inputFile, options) { using (FileStream file = InputFile.OpenRead()) using (ZipReader zipReader = ZipReader.Open(file, new ReaderOptions() { LeaveStreamOpen = false })) { while (zipReader.MoveToNextEntry()) { L.Debug("Moving to file {0} in zip archive.", zipReader.Entry.Key); using (Stream f = zipReader.OpenEntryStream()) using (StreamReader sr = new StreamReader(f)) { CsvReader csv = new CsvReader(sr, true); if (zipReader.Entry.Key.ToLower().StartsWith("dependencies")) { SQLiteConnection conn = new SQLiteConnection("Data Source = {0}; Version = 3; Journal Mode = Off; Synchronous=Off".F(OutputFile.FullName)); string column_names = csv.GetFieldHeaders().Aggregate((s1, s2) => "{0},\"{1}\"".F(s1, s2)); string ddl = "create table Dependencies" + "(" + column_names + ")"; conn.Open(); L.Information("Creating Dependencies table in database {db}", ddl, conn.FileName); L.Debug("Executing SQL {sql} in database {db}", ddl, conn.FileName); SQLiteCommand create_cmd = new SQLiteCommand(ddl, conn); create_cmd.ExecuteNonQuery(); conn.Close(); this.ExtractDependenciesTable(L, csv, OutputFile.FullName); } } } } }
internal void TryLoadTexturePack() { Options.Load(); LauncherSkin.LoadFromOptions(); ClassicMode = Options.GetBool("mode-classic", false); string texDir = Path.Combine(Program.AppDirectory, "texpacks"); string texPack = Options.Get(OptionsKey.DefaultTexturePack) ?? "default.zip"; texPack = Path.Combine(texDir, texPack); if (!File.Exists(texPack)) { texPack = Path.Combine(texDir, "default.zip"); } if (!File.Exists(texPack)) { return; } using (Stream fs = new FileStream(texPack, FileMode.Open, FileAccess.Read, FileShare.Read)) { ZipReader reader = new ZipReader(); reader.ShouldProcessZipEntry = (f) => f == "default.png" || f == "terrain.png"; reader.ProcessZipEntry = ProcessZipEntry; reader.Extract(fs); } }
public void Zip_Deflate_ZipCrypto_Read() { int count = 0; using (Stream stream = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "zipcrypto.zip"))) using (var reader = ZipReader.Open(stream, new ReaderOptions() { Password = "******" })) { while (reader.MoveToNextEntry()) { if (!reader.Entry.IsDirectory) { Assert.Equal(CompressionType.None, reader.Entry.CompressionType); reader.WriteEntryToDirectory(SCRATCH_FILES_PATH, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); count++; } } } Assert.Equal(8, count); }
public void Run() { reader = new ZipReader(); reader.ShouldProcessZipEntry = ShouldProcessZipEntry_Classic; reader.ProcessZipEntry = ProcessZipEntry_Classic; string texDir = Path.Combine(Program.AppDirectory, "texpacks"); string path = Path.Combine(texDir, "default.zip"); using (Stream srcClassic = new MemoryStream(jarClassic), srcModern = new MemoryStream(jar162), dst = new FileStream(path, FileMode.Create, FileAccess.Write)) { writer = new ZipWriter(dst); reader.Extract(srcClassic); // Grab animations and snow animBitmap = new Bitmap(1024, 64, PixelFormat.Format32bppArgb); reader.ShouldProcessZipEntry = ShouldProcessZipEntry_Modern; reader.ProcessZipEntry = ProcessZipEntry_Modern; reader.Extract(srcModern); writer.WriteNewImage(animBitmap, "animations.png"); writer.WriteNewString(animationsTxt, "animations.txt"); using (Bitmap guiBitmap = new Bitmap(new MemoryStream(pngGuiPatch))) { writer.WriteNewImage(guiBitmap, "gui.png"); } animBitmap.Dispose(); writer.WriteCentralDirectoryRecords(); } }
public static void View(string zipFileName) { ZipReader reader = new ZipReader(zipFileName); Console.WriteLine("Archive: {0} ({1} files)", zipFileName, reader.Entries.Count); Console.WriteLine(reader.Comment); string format = "{0,8} {1,8} {2,5} {3,10} {4,5} {5}"; Console.WriteLine(format, " Length ", " Size ", "Ratio", " Date ", "Time ", "Name"); Console.WriteLine(format, "--------", "--------", "-----", "----------", "-----", "----"); foreach (ZipEntry entry in reader.Entries) { if (!entry.IsDirectory) { Console.WriteLine(format, entry.Length, entry.CompressedLength, entry.Ratio.ToString("P0"), entry.ModifiedTime.ToString("yyyy-MM-dd"), entry.ModifiedTime.ToString("hh:mm"), entry.Name); } } reader.Close(); }
public static void ImportGameZip(object sender, EventArgs e) { if (VerifyGameFolderPath()) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Title = "Select a ZIP file containing the DOS game..."; dialog.Filter = "Zip Files (*.zip)|*.zip;*.exe"; if (dialog.ShowDialog(MainForm) == DialogResult.OK) { MainForm.Cursor = Cursors.WaitCursor; string tmpPath = Path.GetTempFileName(); File.Delete(tmpPath); Directory.CreateDirectory(tmpPath); try { ZipReader reader = new ZipReader(dialog.FileName); reader.ExtractTo(tmpPath, true); while (Directory.GetFiles(tmpPath).Length == 0 && Directory.GetDirectories(tmpPath).Length == 1) { tmpPath = Directory.GetDirectories(tmpPath)[0]; } string folderName = Path.GetFileNameWithoutExtension(dialog.FileName); string gamePath = Path.Combine(GameFolderPath, folderName); bool canMove = true; if (Directory.Exists(gamePath)) { DialogResult dialogResult = MessageBox.Show(MainForm, "Game Folder already exists, overwrite it?", "DosBlaster", MessageBoxButtons.OKCancel); if (dialogResult == DialogResult.Cancel) { canMove = false; } else { Directory.Delete(gamePath, true); } } if (canMove) { Directory.Move(tmpPath, gamePath); Game game = new Game(gamePath); game.Name = folderName; game.Category = "Not Set"; MessageBox.Show(MainForm, "Game Imported Successfully", "DosBlaster", MessageBoxButtons.OK); RemoveGameFromListView(game); ListViewItem item = AddGameToListView(game); item.EnsureVisible(); } } catch (Exception ex) { MessageBox.Show(MainForm, ex.Message, "DosBlaster", MessageBoxButtons.OK); if (Directory.Exists(tmpPath)) { Directory.Delete(tmpPath, true); } } MainForm.Cursor = Cursors.Default; } } }
public void Zip_Deflate_WinzipAES_Read() { ResetScratch(); using (Stream stream = File.OpenRead(Path.Combine(TEST_ARCHIVES_PATH, "Zip.deflate.WinzipAES.zip"))) using (var reader = ZipReader.Open(stream, new ReaderOptions() { Password = "******" })) { while (reader.MoveToNextEntry()) { if (!reader.Entry.IsDirectory) { Assert.Equal(CompressionType.Unknown, reader.Entry.CompressionType); reader.WriteEntryToDirectory(SCRATCH_FILES_PATH, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); } } } VerifyFiles(); }
public void TestSharpCompressWithEmptyStream() { ResetScratch(); MemoryStream stream = new NonSeekableMemoryStream(); using (IWriter zipWriter = WriterFactory.Open(stream, ArchiveType.Zip, CompressionType.Deflate)) { zipWriter.Write("foo.txt", new MemoryStream(new byte[0])); zipWriter.Write("foo2.txt", new MemoryStream(new byte[10])); } stream = new MemoryStream(stream.ToArray()); File.WriteAllBytes(Path.Combine(SCRATCH_FILES_PATH, "foo.zip"), stream.ToArray()); using (IReader zipReader = ZipReader.Open(stream)) { while (zipReader.MoveToNextEntry()) { using (EntryStream entry = zipReader.OpenEntryStream()) { MemoryStream tempStream = new MemoryStream(); const int bufSize = 0x1000; byte[] buf = new byte[bufSize]; int bytesRead = 0; while ((bytesRead = entry.Read(buf, 0, bufSize)) > 0) { tempStream.Write(buf, 0, bytesRead); } } } } }
/// <summary> /// Extract the target /// </summary> private void ExtractTarget(string fileName, string output) { var qualifiedFile = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "distribution", fileName); if (!File.Exists(qualifiedFile)) { throw new FileNotFoundException(qualifiedFile); } if (!Directory.Exists(output)) { Directory.CreateDirectory(output); } using (var fs = File.OpenRead(qualifiedFile)) using (var tar = ZipReader.Open(fs)) while (tar.MoveToNextEntry()) { string outName = Path.Combine(output, tar.Entry.Key); if (!Directory.Exists(Path.GetDirectoryName(outName))) { Directory.CreateDirectory(Path.GetDirectoryName(outName)); } Emit.Message("INFO", " {0} > {1}", tar.Entry.Key, outName); if (!tar.Entry.IsDirectory) { using (var ofs = File.Create(outName)) tar.WriteEntryTo(ofs); } } }
// find the content type of a part in the package private String findContentType(ZipReader reader, String target) { String extension = null; if (target.IndexOf(".") != -1) { extension = target.Substring(target.IndexOf(".") + 1); } Stream contentTypes = reader.GetEntry(OOX_CONTENT_TYPE_FILE); XmlReader r = XmlReader.Create(contentTypes); bool overrided = false; String contentType = null; while (r.Read()) { if (r.NodeType == XmlNodeType.Element) { if (r.LocalName == "Default" && extension != null && r.GetAttribute("Extension") == extension && !overrided) { contentType = r.GetAttribute("ContentType"); } else if (r.LocalName == "Override" && r.GetAttribute("PartName") == target) { overrided = true; contentType = r.GetAttribute("ContentType"); } } } if (contentType == null) { throw new NotAnOoxDocumentException("Content type not found for " + target); //throw new PptxValidatorException("Content type not found for " + target); } return(contentType); }
private void LoadInstallInfoZip() { try { //Look for .installinfo file string path = System.IO.Path.GetFullPath(String.Format("{0}.installinfo", System.Diagnostics.Process.GetCurrentProcess().ProcessName)); if (!File.Exists(path)) { MessageBox.Show(String.Format("The file \"{0}\" could not be found!\nThis file should be in the same directory as the executable.\n\nThe installer will now close.", System.IO.Path.GetFileName(path)), "Initialization", MessageBoxButton.OK, MessageBoxImage.Error); Environment.Exit(0); } //Load .installinfo zipManager = new ZipReader(ZipFile.Open(path, ZipArchiveMode.Read)); //Load installerXml from .installinfo if (!zipManager.Exists(GeneralInfo.InstallerXml)) { MessageBox.Show(string.Format("Could not find \"{0}\" in \"{1}\". This file must be at the root level in the archive.\n\nThe installer will now close.", GeneralInfo.InstallerXml, System.IO.Path.GetFileName(path)), "Initialization", MessageBoxButton.OK, MessageBoxImage.Error); Environment.Exit(0); } InstallerInfo = zipManager.DeserializeXmlFromArchive <InstallerXml>(GeneralInfo.InstallerXml); InstallerInfo.Init(); GeneralInfo.InstallerXmlInfo = InstallerInfo; } catch (Exception ex) { MessageBox.Show(ex.Message, "InstallInfo open failed.", MessageBoxButton.OK, MessageBoxImage.Error); Environment.Exit(0); } }
/// <summary> /// Unpacks to file. /// </summary> /// <param name="args">The arguments.</param> /// <param name="file">The file.</param> private static void UnpackToFile(UploadArgs args, HttpPostedFile file) { Assert.ArgumentNotNull(args, "args"); Assert.ArgumentNotNull(file, "file"); string filename = FileUtil.MapPath(TempFolder.GetFilename("temp.zip")); file.SaveAs(filename); using (ZipReader zipReader = new ZipReader(filename)) { foreach (ZipEntry current in zipReader.Entries) { string text = FileUtil.MakePath(args.Folder, current.Name, '\\'); if (current.IsDirectory) { System.IO.Directory.CreateDirectory(text); } else { if (!args.Overwrite) { text = FileUtil.GetUniqueFilename(text); } System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(text)); lock (FileUtil.GetFileLock(text)) { FileUtil.CreateFile(text, current.GetStream(), true); } } } } }
void ExtractTexturePack(string texPack) { using (Stream fs = new FileStream(texPack, FileMode.Open, FileAccess.Read, FileShare.Read)) { ZipReader reader = new ZipReader(); reader.ShouldProcessZipEntry = (f) => f == "default.png" || f == "terrain.png"; reader.ProcessZipEntry = ProcessZipEntry; reader.Extract(fs); } }
public static void ExtractUpdate(byte[] zipData) { Platform.DirectoryCreate("CS_Update"); using (MemoryStream stream = new MemoryStream(zipData)) { ZipReader reader = new ZipReader(); reader.ProcessZipEntry = ProcessZipEntry; reader.Extract(stream); } }
void ExtractTexturePack(string relPath) { using (Stream fs = Platform.FileOpen(relPath)) { ZipReader reader = new ZipReader(); reader.SelectZipEntry = SelectZipEntry; reader.ProcessZipEntry = ProcessZipEntry; reader.Extract(fs); } }
void ExtractTexturePack(string texPack) { using (Stream fs = new FileStream(texPack, FileMode.Open, FileAccess.Read, FileShare.Read)) { ZipReader reader = new ZipReader(); reader.SelectZipEntry = SelectZipEntry; reader.ProcessZipEntry = ProcessZipEntry; reader.Extract(fs); } }
/// <summary> /// main transform which needs the orginal File /// </summary> /// <param name="directionXSL">transform direction</param> /// <param name="resourceResolver">xsl location</param> /// <param name="originalFile">original File</param> /// <param name="inputFile">File after pretreatment</param> /// <param name="outputFile">output file</param> protected void MainTransform(string directionXSL, XmlUrlResolver resourceResolver, string originalFile, string inputFile, string outputFile) { XPathDocument xslDoc; XmlReaderSettings xrs = new XmlReaderSettings(); XmlReader source = null; XmlWriter writer = null; OoxZipResolver zipResolver = null; string zipXMLFileName = "input.xml"; try { //xrs.ProhibitDtd = true; xslDoc = new XPathDocument(((ResourceResolver)resourceResolver).GetInnerStream(directionXSL)); xrs.XmlResolver = resourceResolver; string sr = ZipXMLFile(inputFile); ZipReader archive = ZipFactory.OpenArchive(sr); source = XmlReader.Create(archive.GetEntry(zipXMLFileName)); XslCompiledTransform xslt = new XslCompiledTransform(); XsltSettings settings = new XsltSettings(true, false); xslt.Load(xslDoc, settings, resourceResolver); if (!originalFile.Equals(string.Empty)) { zipResolver = new OoxZipResolver(originalFile, resourceResolver); } XsltArgumentList parameters = new XsltArgumentList(); parameters.XsltMessageEncountered += new XsltMessageEncounteredEventHandler(MessageCallBack); // zip format parameters.AddParam("outputFile", "", outputFile); // writer = new OoxZipWriter(inputFile); writer = new UofZipWriter(outputFile); if (zipResolver != null) { xslt.Transform(source, parameters, writer, zipResolver); } else { xslt.Transform(source, parameters, writer); } } finally { if (writer != null) { writer.Close(); } if (source != null) { source.Close(); } } }
public override bool TestUnZip(string filePath) { try { using (var stream = File.OpenRead(filePath)) { IReader reader = null; if (IsEncryptFile(filePath)) { if (ZipArchive.IsZipFile(filePath)) { reader = ZipReader.Open(stream, new ReaderOptions { Password = "******" }); } else if (RarArchive.IsRarFile(filePath)) { reader = RarReader.Open(stream, new ReaderOptions { Password = "******" }); } } else { reader = ReaderFactory.Open(stream); } var subGuidDir = new DirectoryInfo(Path.Combine(ZipBase.UnZipRootDir, Guid.NewGuid().ToString("N"))); subGuidDir.Create(); if (reader != null) { while (reader.MoveToNextEntry()) { if (!reader.Entry.IsDirectory) { reader.WriteEntryToDirectory(subGuidDir.FullName, new ExtractionOptions { ExtractFullPath = true, Overwrite = true }); } } return(VerifyManager.Verify(subGuidDir.FullName)); } } } catch (Exception ex) { Debug.WriteLine(ex); } return(false); }
/// <summary> /// Opens a Reader for Non-seeking usage /// </summary> /// <param name="stream"></param> /// <param name="options"></param> /// <returns></returns> public static IReader Open(Stream stream, ReaderOptions options = null) { stream.CheckNotNull("stream"); options = options ?? new ReaderOptions() { LeaveStreamOpen = false }; RewindableStream rewindableStream = new RewindableStream(stream); rewindableStream.StartRecording(); if (ZipArchive.IsZipFile(rewindableStream, options.Password)) { rewindableStream.Rewind(true); return(ZipReader.Open(rewindableStream, options)); } rewindableStream.Rewind(false); if (GZipArchive.IsGZipFile(rewindableStream)) { rewindableStream.Rewind(false); GZipStream testStream = new GZipStream(rewindableStream, CompressionMode.Decompress); if (TarArchive.IsTarFile(testStream)) { rewindableStream.Rewind(true); return(new TarReader(rewindableStream, options, CompressionType.GZip)); } rewindableStream.Rewind(true); return(GZipReader.Open(rewindableStream, options)); } rewindableStream.Rewind(false); if (BZip2Stream.IsBZip2(rewindableStream)) { rewindableStream.Rewind(false); BZip2Stream testStream = new BZip2Stream(rewindableStream, CompressionMode.Decompress, true); if (TarArchive.IsTarFile(testStream)) { rewindableStream.Rewind(true); return(new TarReader(rewindableStream, options, CompressionType.BZip2)); } } rewindableStream.Rewind(false); if (RarArchive.IsRarFile(rewindableStream, options)) { rewindableStream.Rewind(true); return(RarReader.Open(rewindableStream, options)); } rewindableStream.Rewind(false); if (TarArchive.IsTarFile(rewindableStream)) { rewindableStream.Rewind(true); return(TarReader.Open(rewindableStream, options)); } throw new InvalidOperationException("Cannot determine compressed stream type. Supported Reader Formats: Zip, GZip, BZip2, Tar, Rar"); }
public List<SyncItem> LoadItems() { var items = new List<SyncItem>(); using (new SecurityDisabler()) { using (new ProxyDisabler()) { var reader = new ZipReader(PackagePath, Encoding.UTF8); ZipEntry entry = reader.GetEntry("package.zip"); using (var stream = new MemoryStream()) { StreamUtil.Copy(entry.GetStream(), stream, 0x4000); reader = new ZipReader(stream); foreach (ZipEntry zipEntry in reader.Entries) { var entryData = new ZipEntryData(zipEntry); try { if (entryData.Key.EndsWith("/xml")) { string xml = new StreamReader(entryData.GetStream().Stream, Encoding.UTF8).ReadToEnd(); if (!string.IsNullOrWhiteSpace(xml)) { XmlDocument document = XmlUtil.LoadXml(xml); if (document != null) { SyncItem loadedItem = LoadItem(document); if (loadedItem != null) { items.Add(loadedItem); } } } } } catch (Exception) { Console.WriteLine("Unable to load xml from file {0}", entryData.Key); } } } } } Console.WriteLine("Read {0} items from package {1}", items.Count, PackagePath); return items; }
/// <summary> /// 按文件名打开压缩文件. /// </summary> /// <param name="name">压缩文件名</param> public ZipFile(string name) { this.zipName = name; this.baseStream = new FileStream(this.zipName, FileMode.Open); this.thisReader = new ZipReader(this.baseStream);//, Path.GetFileName(this.zipName)); //zipEntries = new List<ZipEntry>(); this.zipEntries = this.thisReader.GetAllEntries(); }
public new void Process(UploadArgs args) { if (Sitecore.UIUtil.IsIE()) { // We need to use the original functionality for IE base.Process(args); return; } Assert.ArgumentNotNull((object)args, "args"); if (args.Destination == UploadDestination.File) return; foreach (string index in (NameObjectCollectionBase)args.Files) { HttpPostedFile file = args.Files[index]; if (!string.IsNullOrEmpty(file.FileName)) { if (UploadProcessor.IsUnpack(args, file)) { ZipReader zipReader = new ZipReader(file.InputStream); try { foreach (ZipEntry zipEntry in zipReader.Entries) { if (!zipEntry.IsDirectory && zipEntry.Size > Settings.Media.MaxSizeInDatabase) { string text = file.FileName + "/" + zipEntry.Name; HttpContext.Current.Response.Write("<html><head><script type=\"text/JavaScript\" language=\"javascript\">window.top.scForm.browser.getTopModalDialog().frames[0].scForm.postRequest(\"\", \"\", \"\", 'ShowFileTooBig(" + StringUtil.EscapeJavascriptString(text) + ")')</script></head><body>Done</body></html>"); args.ErrorText = string.Format("The file \"{0}\" is too big to be uploaded. The maximum size for uploading files is {1}.", (object)text, (object)MainUtil.FormatSize(Settings.Media.MaxSizeInDatabase)); args.AbortPipeline(); return; } } } finally { file.InputStream.Position = 0L; } } else if ((long)file.ContentLength > Settings.Media.MaxSizeInDatabase) { string fileName = file.FileName; HttpContext.Current.Response.Write("<html><head><script type=\"text/JavaScript\" language=\"javascript\">window.top.scForm.browser.getTopModalDialog().frames[0].scForm.postRequest(\"\", \"\", \"\", 'ShowFileTooBig(" + StringUtil.EscapeJavascriptString(fileName) + ")')</script></head><body>Done</body></html>"); args.ErrorText = string.Format("The file \"{0}\" is too big to be uploaded. The maximum size for uploading files is {1}.", (object)fileName, (object)MainUtil.FormatSize(Settings.Media.MaxSizeInDatabase)); args.AbortPipeline(); break; } } } }
public PackageManifest GetManifest(string filename) { var manifest = new PackageManifest(); ZipReader reader; try { reader = new ZipReader(filename, Encoding.UTF8); } catch (Exception exception) { throw new InvalidOperationException("Failed to open package", exception); } string tempFileName = Path.GetTempFileName(); ZipEntry entry = reader.GetEntry("package.zip"); if (entry != null) { using (FileStream stream = File.Create(tempFileName)) { StreamUtil.Copy(entry.GetStream(), stream, 0x4000); } reader.Dispose(); reader = new ZipReader(tempFileName, Encoding.UTF8); } try { foreach (ZipEntry entry2 in reader.Entries) { var data = new ZipEntryData(entry2); var packageManifestEntry = ZipEntryDataParser.GetManifestEntry(data.Key); if (! (packageManifestEntry is PackageManifestEntryNotFound)) { manifest.Entries.Add(packageManifestEntry); } } } finally { reader.Dispose(); File.Delete(tempFileName); } return manifest; }
public AntidotePackageDefinition GetSources() { var itemsIds = new List<AntidoteItemSourceDefinition>(); var filesInfo = new List<AntidoteFileSourceDefinition>(); ZipReader zipReader = new ZipReader(filename, Encoding.UTF8); string tempFileName = Path.GetTempFileName(); ZipEntry entry1 = zipReader.GetEntry("package.zip"); if (entry1 != null) { using (FileStream fileStream = File.Create(tempFileName)) StreamUtil.Copy(entry1.GetStream(), fileStream, 16384); zipReader.Dispose(); zipReader = new ZipReader(tempFileName, Encoding.UTF8); } try { foreach (ZipEntry entry2 in zipReader.Entries) { if (entry2.IsItem()) { itemsIds.Add((AntidoteItemSourceDefinition)entry2); } if (entry2.IsFile()) { string filePath = Path.Combine(HostingEnvironment.ApplicationHost.GetPhysicalPath(), entry2.GetFilePath()); filesInfo.Add(new AntidoteFileSourceDefinition { FileInfo = new FileInfo(filePath) }); } } return new AntidotePackageDefinition { FilesInfo = filesInfo, ItemsId = itemsIds.Distinct() }; } finally { zipReader.Dispose(); File.Delete(tempFileName); } }
/// <summary> /// /// </summary> /// <param name="packageFileName"></param> /// <returns></returns> private project ExtractPackageAndGetProjectInformation(string packageFileName) { project projectInformation = null; ZipReader reader = null; string tempFileName = string.Empty; try { reader = new ZipReader(packageFileName, Encoding.UTF8); tempFileName = Path.GetTempFileName(); ZipEntry entry = reader.GetEntry("package.zip"); if (entry != null) { using (FileStream stream = File.Create(tempFileName)) { StreamUtil.Copy(entry.GetStream(), stream, 0x4000); } reader.Dispose(); reader = new ZipReader(tempFileName, Encoding.UTF8); } // Get Project XML File entry = reader.GetEntry("installer/project"); using (MemoryStream memoryStream = new MemoryStream()) { StreamUtil.Copy(entry.GetStream(), memoryStream, 0x4000); // Let's go to start of stream memoryStream.Seek(0, SeekOrigin.Begin); // Convert XML to class // Package can contain list of // Items // Files XmlSerializer serializer = new XmlSerializer(typeof(project)); projectInformation = (project)serializer.Deserialize(memoryStream); } } catch (Exception ex) { projectInformation = null; Sitecore.Diagnostics.Log.Error("While extracting package and getting information something went wrong", ex, this); } finally { if (reader != null) reader.Dispose(); if (!string.IsNullOrEmpty(tempFileName)) File.Delete(tempFileName); } return projectInformation; }
/// <summary> /// Unpacks to file. /// </summary> /// <param name="args">The arguments.</param> /// <param name="file">The file.</param> private static void UnpackToFile(UploadArgs args, HttpPostedFile file) { Assert.ArgumentNotNull(args, "args"); Assert.ArgumentNotNull(file, "file"); var filename = FileUtil.MapPath(TempFolder.GetFilename("temp.zip")); file.SaveAs(filename); using (var zipReader = new ZipReader(filename)) { foreach (var zipEntry in zipReader.Entries) { var str = FileUtil.MakePath(args.Folder, zipEntry.Name, '\\'); if (zipEntry.IsDirectory) { Directory.CreateDirectory(str); } else { if (!args.Overwrite) str = FileUtil.GetUniqueFilename(str); Directory.CreateDirectory(Path.GetDirectoryName(str)); lock (FileUtil.GetFileLock(str)) FileUtil.CreateFile(str, zipEntry.GetStream(), true); } } } }
/// <summary> /// Performs the action that is passed while reading the Sitecore package. /// </summary> /// <param name="action"></param> private static void ApplyToZipEntries(Action<ZipEntryData> action) { using (new SecurityDisabler()) { using (new ProxyDisabler()) { ZipReader reader = new ZipReader(file.FullName, Encoding.UTF8); ZipEntry entry = reader.GetEntry("package.zip"); using (MemoryStream stream = new MemoryStream()) { StreamUtil.Copy(entry.GetStream(), stream, 0x4000); reader = new ZipReader(stream); foreach (ZipEntryData entryData in reader.Entries.Select(zipEntry => new ZipEntryData(zipEntry))) { action(entryData); } } } } }
/// <summary> /// Unpacks to database. /// /// </summary> private void UnpackToDatabase(List<S3MediaUploadResult> list) { Assert.ArgumentNotNull((object)list, "list"); string str = FileUtil.MapPath(TempFolder.GetFilename("temp.zip")); this.File.SaveAs(str); try { using (ZipReader zipReader = new ZipReader(str)) { foreach (ZipEntry zipEntry in zipReader.Entries) { if (!zipEntry.IsDirectory) { S3MediaUploadResult S3MediaUploadResult = new S3MediaUploadResult(); list.Add(S3MediaUploadResult); S3MediaUploadResult.Path = FileUtil.MakePath(this.Folder, zipEntry.Name, '/'); S3MediaUploadResult.ValidMediaPath = MediaPathManager.ProposeValidMediaPath(S3MediaUploadResult.Path); MediaCreatorOptions options = new MediaCreatorOptions() { Language = this.Language, Versioned = this.Versioned, KeepExisting = !this.Overwrite, Destination = S3MediaUploadResult.ValidMediaPath, FileBased = this.FileBased, Database = this.Database }; options.Build(GetMediaCreatorOptionsArgs.UploadContext); Stream stream = zipEntry.GetStream(); S3MediaUploadResult.Item = MediaManager.Creator.CreateFromStream(stream, S3MediaUploadResult.Path, options); } } } } finally { FileUtil.Delete(str); } }