Provides a stream metaphor for reading zip files.

This class provides an alternative programming model for reading zip files to the one enabled by the ZipFile class. Use this when reading zip files, as an alternative to the ZipFile class, when you would like to use a Stream class to read the file.

Some application designs require a readable stream for input. This stream can be used to read a zip file, and extract entries.

Both the ZipInputStream class and the ZipFile class can be used to read and extract zip files. Both of them support many of the common zip features, including Unicode, different compression levels, and ZIP64. The programming models differ. For example, when extracting entries via calls to the GetNextEntry() and Read() methods on the ZipInputStream class, the caller is responsible for creating the file, writing the bytes into the file, setting the attributes on the file, and setting the created, last modified, and last accessed timestamps on the file. All of these things are done automatically by a call to ZipEntry.Extract(). For this reason, the ZipInputStream is generally recommended for when your application wants to extract the data, without storing that data into a file.

Aside from the obvious differences in programming model, there are some differences in capability between the ZipFile class and the ZipInputStream class.

ZipFile can be used to create or update zip files, or read and extract zip files. ZipInputStream can be used only to read and extract zip files. If you want to use a stream to create zip files, check out the ZipOutputStream. ZipInputStream cannot read segmented or spanned zip files. ZipInputStream will not read Zip file comments. When reading larger files, ZipInputStream will always underperform ZipFile. This is because the ZipInputStream does a full scan on the zip file, while the ZipFile class reads the central directory of the zip file.
Inheritance: Stream
Example #1
1
        public byte[] Decrypt(byte[] Data, byte[] Key)
        {
            string StringContent = Encoding.UTF8.GetString(Data);
            var ByteArray = ToByteArray(StringContent.Replace("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body><data>", "").Replace("</data></s:Body></s:Envelope>", ""));

            MemoryStream s = new MemoryStream(ByteArray);
            using (ZipInputStream InputStream = new ZipInputStream(s))
            {
                InputStream.Password = Encoding.UTF8.GetString(Key);
                InputStream.GetNextEntry();

                return Encoding.Unicode.GetBytes(new StreamReader(InputStream, Encoding.Unicode).ReadToEnd());
            }
        }
Example #2
0
        public IEnumerable<FileEntry> ListFiles(Stream strm, Callbacks callbacks)
        {
            ZipEntry ze;
            ZipInputStream zstrm = new ZipInputStream(strm, true);
            List<FileEntry> results = new List<FileEntry>();
            FileEntry fe;

            SetupZIPParams();
            while (true)
            {
                ze = zstrm.GetNextEntry();
                if (ze == null)
                    break;

                if (ze.IsDirectory)
                    continue;

                fe = new FileEntry();
                fe.Filename = ze.FileName;
                fe.UncompressedSize = ze.UncompressedSize;
                fe.Timestamp = ze.LastModified;
                results.Add(fe);
            };

            return results;
        }
        public ZipInputStream Extract(ZipInputStream extractionStream)
        {
            using (var zip = new ZipFile(this.Path))
            {
                zip.ForEach(x => x.Extract(extractionStream));
            }

            return extractionStream;
        }
Example #4
0
		public int Decompress(PointCloudTile tile, byte[] compressedBuffer, int count, byte[] uncompressedBuffer)
		{
			MemoryStream compressedStream = new MemoryStream(compressedBuffer, 0, count, false);

			int uncompressedBytes = 0;
			using (ZipInputStream zipStream = new ZipInputStream(compressedStream, true))
			{
				zipStream.GetNextEntry();
				uncompressedBytes = zipStream.Read(uncompressedBuffer, 0, uncompressedBuffer.Length);
			}

			return uncompressedBytes;
		}
Example #5
0
 /// <summary>
 /// Read epub from inputstream
 /// </summary> 
 /// <param name="zipInputStream">the inputstream from which to read the epub</param>
 /// <param name="encoding"></param>
 public Book readEpub(ZipInputStream zipInputStream, String encoding)
 {
     Book result = new Book();
     Resources resources = readResources(zipInputStream, encoding);
     handleMimeType(result, resources);
     String packageResourceHref = getPackageResourceHref(resources);
     Resource packageResource = processPackageResource(packageResourceHref, result, resources);
     result.setOpfResource(packageResource);
     Resource ncxResource = processNcxResource(packageResource, result);
     result.setNcxResource(ncxResource);
     result = postProcessBook(result);
     return result;
 }
        public void ReadCompressedZip(string filepath)
        {
            while (BackgroundWriting) ;

            ZipInputStream instream = new ZipInputStream(filepath);
            BinaryFormatter formatter = new BinaryFormatter();
            instream.GetNextEntry();
            searchDump = new TCPTCPGecko.Dump((uint)formatter.Deserialize(instream), (uint)formatter.Deserialize(instream));
            instream.Read(searchDump.mem, 0, (int)(searchDump.EndAddress - searchDump.StartAddress));

            instream.GetNextEntry();
            resultsList = (System.Collections.Generic.List<UInt32>)formatter.Deserialize(instream);

            instream.Close();
            instream.Dispose();
        }
 private static byte[] ExtractLogoBin(string zipfilename)
 {
     byte[] buffer = null;
     using (var input = new ZipInputStream(zipfilename))
     {
         ZipEntry e;
         while ((e = input.GetNextEntry()) != null)
         {
             if (e.IsDirectory) continue;
             if (Path.GetFileName(e.FileName) != "logo.bin") continue;
             buffer = new byte[e.UncompressedSize];
             input.Read(buffer, 0, buffer.Length);
             break;
         }
     }
     return buffer;
 }
Example #8
0
		/// <summary>
		/// Initializes a new instance of the <see cref="WF.Compiler.Parser"/> class.
		/// Checks also, if the gwz could be found, and if it contains a lua file
		/// </summary>
		/// <param name='filename'>
		/// Filename.
		/// </param>
		public Parser ( string filename )
		{
			// Check if fileName exists
			if ( !File.Exists ( filename ) )
			{
				// Try, if we could append a .gwz to the filename to get the file than
				if ( !File.Exists ( filename + ".gwz" ) )
					throw new FileNotFoundException ( "File not found", filename );
				else
					this.filenameGwz = filename + ".gwz";
			}
			else
			{
				// Save fileName
				this.filenameGwz = filename;
			}

			// Now open gwz file and read all relevant data
			ZipInputStream zipInput = new ZipInputStream ( File.OpenRead ( filename ) );

			ZipEntry zipEntry;

			while ( ( zipEntry = zipInput.GetNextEntry () ) != null ) 
			{
				switch ( Path.GetExtension ( zipEntry.FileName ).ToLower () )
				{
					case ".lua":
						filenameLua = zipEntry.FileName;
						break;
					case ".gwi":
						filenameInfo = zipEntry.FileName;
						break;
					default:
						files.Add ( zipEntry.FileName.ToLower () );
						break;
				}
			}

			zipInput.Close ();

			// Is gwz file a valid gwz file
			if ( filenameLua == null )
				throw new FileNotFoundException ( "Lua file not found", filename );
		}
Example #9
0
        private void ZipOk(POIFSFileSystem fs, Decryptor d)
        {
            ZipInputStream zin = new ZipInputStream(d.GetDataStream(fs));
            while (true)
            {
                int pos = zin.ReadByte();
                if (pos == -1)
                    break;
            //    ZipEntry entry = zin.GetNextEntry();
            //    if (entry == null)
            //    {
            //        break;
            //    }

                //while (zin.available() > 0)
                //{
                //    zin.skip(zin.available());
                //}
            }
        }
Example #10
0
 // Methods
 public void Dissect()
 {
     byte[] buffer = new byte[0x800];
     using (ZipInputStream stream2 = new ZipInputStream(this.MS))
     {
         for (ZipEntry entry = stream2.GetNextEntry(); entry != null; entry = stream2.GetNextEntry())
         {
             if (!entry.IsDirectory)
             {
                 ZipFileEntry item = new ZipFileEntry
                 {
                     Name = entry.FileName
                 };
                 MemoryStream stream = new MemoryStream();
                 if (Strings.Len(this.Pass) > 0)
                 {
                     stream2.Password = this.Pass;
                 }
                 if (entry.UncompressedSize > 0L)
                 {
                     for (int i = stream2.Read(buffer, 0, buffer.Length); i > 0; i = stream2.Read(buffer, 0, buffer.Length))
                     {
                         stream.Write(buffer, 0, i);
                     }
                 }
                 item.contents = stream.ToArray();
                 this.Files.Add(item, null, null, null);
             }
             else
             {
                 ZipFileEntry entry3 = new ZipFileEntry
                 {
                     IsDir = true,
                     Name = entry.FileName
                 };
             }
         }
     }
 }
Example #11
0
 /// <summary>
 /// Unzips a stream and calls an action for each unzipped file.
 /// </summary>
 /// <param name="zip">The zip byte array.</param>
 /// <param name="unzipAction">The action to perform with each unzipped file.</param>
 public static void Unzip(Stream zip, Action<Path, byte[]> unzipAction)
 {
     using (var zipStream = new ZipInputStream(zip)) {
         ZipEntry theEntry;
         while ((theEntry = zipStream.GetNextEntry()) != null) {
             if (!theEntry.IsDirectory && theEntry.FileName != "") {
                 using (var streamWriter = new MemoryStream()) {
                     var data = new byte[2048];
                     while (true) {
                         var size = zipStream.Read(data, 0, data.Length);
                         if (size > 0)
                             streamWriter.Write(data, 0, size);
                         else
                             break;
                     }
                     streamWriter.Close();
                     unzipAction(new Path(theEntry.FileName), streamWriter.ToArray());
                 }
             }
         }
     }
 }
Example #12
0
        protected void btnImport_Click(object sender, EventArgs e)
        {
            if (!IsValid) return;

            var imported = new List<string>();

            using (var zip = new ZipInputStream(fupImport.FileContent))
            {
                for (var entry = zip.GetNextEntry(); entry != null; entry = zip.GetNextEntry())
                {
                    if (entry.IsDirectory) continue;
                    var path = rootPath + '/' + entry.FileName;
                    fileSystem.WriteFile(path, zip);
                    imported.Add(path);
                }
            }

            rptImportedFiles.DataSource = imported;
            rptImportedFiles.DataBind();

            mvwImport.ActiveViewIndex = 1;

            Refresh(Selection.SelectedItem, ToolbarArea.Navigation);
        }
Example #13
0
        public void ZIS_ZOS_VaryCompression()
        {
            string resourceDir = Path.Combine(SourceDir, TestUtilities.GetBinDir("Zip.Portable.Tests"), "Resources");
            var filesToAdd = Directory.GetFiles(resourceDir);

            Func<int, int, bool> chooseCompression = (ix, cycle) => {
                var name = Path.GetFileName(filesToAdd[ix]);
                switch (cycle)
                {
                    case 0:
                        return !(name.EndsWith(".zip") ||
                                 name.EndsWith(".docx") ||
                                 name.EndsWith(".xslx"));
                    case 1:
                        return ((ix%2)==0);

                    default:
                        return (ix == filesToAdd.Length - 1);
                }
            };

            // Three cycles - three different ways to vary compression
            for (int k=0; k < 3; k++)
            {
                string zipFileToCreate = String.Format("VaryCompression-{0}.zip", k);

                TestContext.WriteLine("");
                TestContext.WriteLine("Creating zip, cycle {0}", k);
                using (var fileStream = File.OpenWrite(zipFileToCreate))
                {
                    using (var zos = new ZipOutputStream(fileStream, true))
                    {
                        for (int i=0; i < filesToAdd.Length; i++)
                        {
                            var file = filesToAdd[i];
                            var shortName = Path.GetFileName(file);
                            bool compress = chooseCompression(i, k);

                            if (compress)
                                zos.CompressionLevel = Ionic.Zlib.CompressionLevel.Default;
                            else
                                zos.CompressionLevel = Ionic.Zlib.CompressionLevel.None;

                            zos.PutNextEntry(shortName);
                            using (var input = File.OpenRead(file))
                            {
                                CopyStream(input, zos);
                            }
                        }
                    }
                }

                TestContext.WriteLine("");
                TestContext.WriteLine("Extracting cycle {0}", k);
                string extractDir = "extract-" + k;
                Directory.CreateDirectory(extractDir);
                using (var raw = File.OpenRead(zipFileToCreate))
                {
                    using (var input = new ZipInputStream(raw))
                    {
                        ZipEntry e;
                        while ((e = input.GetNextEntry()) != null)
                        {
                            TestContext.WriteLine("entry: {0}", e.FileName);
                            string outputPath = Path.Combine(extractDir, e.FileName);
                            if (e.IsDirectory)
                            {
                                // create the directory
                                Directory.CreateDirectory(outputPath);
                            }
                            else
                            {
                                // create the file
                                using (var output = File.Create(outputPath))
                                {
                                    CopyStream(input,output);
                                }
                            }
                        }
                    }
                }

                string[] filesUnzipped = Directory.GetFiles(extractDir);
                Assert.AreEqual<int>(filesToAdd.Length, filesUnzipped.Length,
                                     "Incorrect number of files extracted.");

            }
        }
Example #14
0
        public void _Internal_Streams_WinZip_Zip(int fodderOption, string password, string label)
        {
            if (!WinZipIsPresent)
                throw new Exception("skipping test [_Internal_Streams_WinZip_Zip] : winzip is not present");

            int[] fileCounts = { 1, 2, _rnd.Next(8) + 6, _rnd.Next(18) + 16, _rnd.Next(48) + 56 };

            for (int m = 0; m < fileCounts.Length; m++)
            {
                string dirToZip = String.Format("trial{0:D2}", m);
                if (!Directory.Exists(dirToZip)) Directory.CreateDirectory(dirToZip);

                int fileCount = fileCounts[m];
                string zipFileToCreate = Path.Combine(TopLevelDir,
                                                      String.Format("Streams_Winzip_Zip.{0}.{1}.{2}.zip", fodderOption, label, m));

                string[] files = null;
                if (fodderOption == 0)
                {
                    // zero length files
                    files = new string[fileCount];
                    for (int i = 0; i < fileCount; i++)
                        files[i] = CreateZeroLengthFile(i, dirToZip);
                }
                else if (fodderOption == 1)
                    files = TestUtilities.GenerateFilesFlat(dirToZip, fileCount, 100, 72000);
                else
                {
                    // mixed
                    files = new string[fileCount];
                    for (int i = 0; i < fileCount; i++)
                    {
                        if (_rnd.Next(3) == 0)
                            files[i] = CreateZeroLengthFile(i, dirToZip);
                        else
                        {
                            files[i] = Path.Combine(dirToZip, String.Format("nonzero{0:D4}.txt", i));
                            TestUtilities.CreateAndFillFileText(files[i], _rnd.Next(60000) + 100);
                        }
                    }
                }

                // Create the zip archive via WinZip.exe
                string pwdOption = String.IsNullOrEmpty(password) ? "" : "-s" + password;
                string formatString = "-a -p {0} -yx \"{1}\" \"{2}\\*.*\"";
                string wzzipOut = this.Exec(wzzip, String.Format(formatString, pwdOption, zipFileToCreate, dirToZip));

                // Verify the number of files in the zip
                Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), files.Length,
                                     "Incorrect number of entries in the zip file.");

                // extract the files
                string extractDir = String.Format("extract{0:D2}", m);
                Directory.CreateDirectory(extractDir);
                byte[] buffer = new byte[2048];
                int n;

                using (var raw = File.OpenRead(zipFileToCreate))
                {
                    using (var input = new ZipInputStream(raw))
                    {
                        input.Password = password;
                        ZipEntry e;
                        while ((e = input.GetNextEntry()) != null)
                        {
                            TestContext.WriteLine("entry: {0}", e.FileName);
                            string outputPath = Path.Combine(extractDir, e.FileName);
                            if (e.IsDirectory)
                            {
                                // create the directory
                                Directory.CreateDirectory(outputPath);
                                continue;
                            }
                            // create the file
                            using (var output = File.Create(outputPath))
                            {
                                while ((n = input.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    output.Write(buffer, 0, n);
                                }
                            }

                            // we don't set the timestamps or attributes
                            // on the file/directory.
                        }
                    }
                }

                string[] filesUnzipped = Directory.GetFiles(extractDir);

                // Verify the number of files extracted
                Assert.AreEqual<int>(files.Length, filesUnzipped.Length,
                                     "Incorrect number of files extracted.");
            }
        }
Example #15
0
        public void _Internal_Streams_7z_Zip(int flavor, string label)
        {
            if (!SevenZipIsPresent)
            {
                TestContext.WriteLine("skipping test [_Internal_Streams_7z_Zip] : SevenZip is not present");
                return;
            }

            int[] fileCounts = { 1, 2, _rnd.Next(8) + 6, _rnd.Next(18) + 16, _rnd.Next(48) + 56 };

            for (int m = 0; m < fileCounts.Length; m++)
            {
                string dirToZip = String.Format("trial{0:D2}", m);
                if (!Directory.Exists(dirToZip)) Directory.CreateDirectory(dirToZip);

                int fileCount = fileCounts[m];
                string zipFileToCreate = Path.Combine(TopLevelDir,
                                                      String.Format("Streams_7z_Zip.{0}.{1}.{2}.zip", flavor, label, m));

                string[] files = null;
                if (flavor == 0)
                {
                    // zero length files
                    files = new string[fileCount];
                    for (int i = 0; i < fileCount; i++)
                        files[i] = CreateZeroLengthFile(i, dirToZip);
                }
                else if (flavor == 1)
                    files = TestUtilities.GenerateFilesFlat(dirToZip, fileCount, 100, 72000);
                else
                {
                    // mixed
                    files = new string[fileCount];
                    for (int i = 0; i < fileCount; i++)
                    {
                        if (_rnd.Next(3) == 0)
                            files[i] = CreateZeroLengthFile(i, dirToZip);
                        else
                        {
                            files[i] = Path.Combine(dirToZip, String.Format("nonzero{0:D4}.txt", i));
                            TestUtilities.CreateAndFillFileText(files[i], _rnd.Next(60000) + 100);
                        }
                    }
                }

                // Create the zip archive via 7z.exe
                this.Exec(sevenZip, String.Format("a \"{0}\" \"{1}\"", zipFileToCreate, dirToZip));

                // Verify the number of files in the zip
                Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), files.Length,
                                     "Incorrect number of entries in the zip file.");

                // extract the files
                string extractDir = String.Format("extract{0:D2}", m);
                byte[] buffer = new byte[2048];
                int n;
                using (var raw = File.OpenRead(zipFileToCreate))
                {
                    using (var input = new ZipInputStream(raw))
                    {
                        ZipEntry e;
                        while ((e = input.GetNextEntry()) != null)
                        {
                            TestContext.WriteLine("entry: {0}", e.FileName);
                            string outputPath = Path.Combine(extractDir, e.FileName);
                            if (e.IsDirectory)
                            {
                                // create the directory
                                Directory.CreateDirectory(outputPath);
                            }
                            else
                            {
                                // create the file
                                using (var output = File.Create(outputPath))
                                {
                                    while ((n = input.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        output.Write(buffer, 0, n);
                                    }
                                }
                            }

                            // we don't set the timestamps or attributes
                            // on the file/directory.
                        }
                    }
                }

                // winzip does not include the base path in the filename;
                // 7zip does.
                string[] filesUnzipped = Directory.GetFiles(Path.Combine(extractDir, dirToZip));

                // Verify the number of files extracted
                Assert.AreEqual<int>(files.Length, filesUnzipped.Length,
                                     "Incorrect number of files extracted.");
            }
        }
        /// <summary>
        /// Downloads the data for the specified show and returns the path to the file.
        /// </summary>
        /// <param name="show">
        /// The show to download data for. 
        /// </param>
        /// <returns>
        /// The path to the downloaded file. 
        /// </returns>
        public static string DownloadShowEpisodes(TvShow show)
        {
            for (int i = 0; i < RetryCount; i++)
            {
                try
                {
                    var webClient = new WebClient();
                    string showAddress = Mirror + ApiLoc + "/series/" + show.TvdbId + "/all/en.zip";
                    string savePath = Tvdb.CacheDirectory + show.TvdbId + ".xml";

                    if (!Directory.Exists(Tvdb.CacheDirectory))
                    {
                        Directory.CreateDirectory(Tvdb.CacheDirectory);
                    }

                    if (File.Exists(savePath))
                    {
                        File.Delete(savePath);
                    }

                    webClient.DownloadFile(showAddress, savePath + ".zip");

                    // Download the zip file to a zip stream
                    using (var stream = new ZipInputStream(savePath + ".zip"))
                    {
                        ZipEntry e;
                        var buffer = new byte[2048];

                        // Loop through all the entries looking for en.xml.
                        while ((e = stream.GetNextEntry()) != null)
                        {
                            if (!e.FileName.Equals("en.xml"))
                            {
                                while (stream.Read(buffer, 0, buffer.Length) > 0)
                                {
                                }
                            }

                            // Write the file to savePath.
                            using (var output = File.Open(savePath, FileMode.Create, FileAccess.ReadWrite))
                            {
                                int n;
                                while ((n = stream.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    output.Write(buffer, 0, n);
                                }
                            }

                            break;
                        }
                    }

                    return savePath;
                }
                catch (WebException)
                {
                    // Suppress any exceptions so the download can be retried.
                }
            }

            throw new Exception("Unable to download show data for " + show.Name);
        }
Example #17
0
        void Parse()
        {
            using (var stream = System.IO.File.OpenRead(Name.GetPath()))
            {
                var input = new ZipInputStream(stream);

                ZipEntry entry;
                while ((entry = input.GetNextEntry()) != null)
                {
                    Trace.WriteLine("Reading Entry: " + entry.FileName);
                    var name = entry.FileName.Split('/');

                    if (name.Length == 1) // a file
                    {
                        byte[] data = input.ReadToEnd();
                        Trace.WriteLine("Read: " + data.Length + " bytes");
                        var fn = FileName.GetFileName(this.Name, name[0]);
                        _files.Add(name[0], new ZippedFile(fn, data));
                    }
                    else
                    {
                        var first = name.First();
                        var parent = new ZippedDirectory(DirectoryName.GetDirectoryName(this.Name, first), this);
                        _directories.Add(first, parent);
                        var rest = name.Skip(1).Take(name.Length - 2);
                        var queue = new Queue<string>(rest);

                        foreach (var item in queue)
                        {
                            var dir = new ZippedDirectory(DirectoryName.GetDirectoryName(parent.Name, item), parent);
                            parent = dir;
                        }
                        var file = name.Last();

                        byte[] data = input.ReadToEnd();
                        Trace.WriteLine("Read: " + data.Length + " bytes");
                        //neds to be added
                        var zipfile = new ZippedFile(FileName.GetFileName(parent.Name, file), data);
                        parent.AddFile(file, zipfile);
                    }
                }
            }
            _parse = () => { };
        }
        private void ExtractZipBall(string zipFileToExtract, string destinationDirectory)
        {
            //Clean up the existing repository
            if (Directory.Exists(destinationDirectory))
            {
                DirectoryInfo directory = new DirectoryInfo(destinationDirectory);
                foreach (FileInfo file in directory.GetFiles()) file.Delete();
                foreach (System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
            }
            else
            {
                Directory.CreateDirectory(destinationDirectory);
            }

            //using (var zipFile = ZipFile.Read(zipFileToExtract))
            //{
            //    zipFile.ExtractAll(destinationDirectory, ExtractExistingFileAction.OverwriteSilently);
            //}

            using (ZipInputStream zipStream = new ZipInputStream(zipFileToExtract))
            {
                string zipRootDirectoryName = string.Empty;
                ZipEntry zipEntry = zipStream.GetNextEntry();
                if (zipEntry == null)
                {
                    return;
                }
                else
                {
                    if (zipEntry.IsDirectory)
                    {
                        zipRootDirectoryName = zipEntry.FileName;
                    }
                }

                while ((zipEntry = zipStream.GetNextEntry()) != null)
                {
                    string zipEntryPath = zipEntry.FileName;
                    if (!string.IsNullOrEmpty(zipRootDirectoryName))
                    {
                        zipEntryPath = zipEntryPath.Replace(zipRootDirectoryName, string.Empty);
                    }

                    if (zipEntry.IsDirectory)
                    {
                        Directory.CreateDirectory(Path.Combine(destinationDirectory, zipEntryPath));
                        continue;
                    }

                    string filename = Path.Combine(destinationDirectory, zipEntryPath);
                    using (var fileStream = File.OpenWrite(filename))
                    {
                        CopyStream(zipStream, fileStream);
                    }
                }
            }
        }
        void parse()
        {
            using (var stream = System.IO.File.OpenRead(Name.GetPath()))
            {
                var input = new ZipInputStream(stream);

                ZipEntry entry;
                while ((entry = input.GetNextEntry()) != null)
                {
                    Trace.WriteLine("Reading Entry: " + entry.FileName);
                    if (entry.IsDirectory)
                    {
                        parseDirectory(input, entry);
                    }
                    else
                    {
                        parseFile(input, entry);
                    }

                }
            }
            _parse = () => { };
        }
 void parseDirectory(ZipInputStream input, ZipEntry entry)
 {
 }
Example #21
0
        private bool ReadEntries(ZipInputStream input)
        {
            ZipEntry e;

            try
            {
                while ((e = input.GetNextEntry()) != null)
                {
                    if (e.IsDirectory) continue;
                }
            }
            catch
            {
                return false;
            }

            return true;
        }
Example #22
0
 /// <summary>
 /// Read epub from inputstream
 /// </summary>
 /// <param name="zipInputStream"></param>
 public Book readEpub(ZipInputStream zipInputStream)
 {
     return readEpub(zipInputStream, Constants.ENCODING);
 }
Example #23
0
 /// 
 /// <param name="in"></param>
 /// <param name="defaultHtmlEncoding"></param>
 private Resources readResources(ZipInputStream zipInputStream, String defaultHtmlEncoding)
 {
     Resources result = new Resources();
     for (ZipEntry zipEntry = zipInputStream.GetNextEntry(); zipEntry != null; zipEntry = zipInputStream.GetNextEntry())
     {
         if (zipEntry.IsDirectory)
         {
             continue;
         }
         Resource resource = ResourceUtil.createResource(zipEntry, zipInputStream);
         if (resource.getMediaType() == MediatypeService.XHTML)
         {
             resource.setInputEncoding(defaultHtmlEncoding);
         }
         result.add(resource);
     }
     return result;
 }
        void parseFile(ZipInputStream input,ZipEntry entry)
        {
            var name = entry.FileName.Split('/');

            if (name.Length == 1) // a file
            {
                byte[] data = input.ReadToEnd();
                Trace.WriteLine("Read: " + data.Length + " bytes");
                var fn = FileName.GetFileName(Name, name[0]);
                AddFile(new ZippedFile(fn, data));
            }
            else
            {
                var first = name.First();
                var parent = new ZippedDirectory(DirectoryName.GetDirectoryName(Name, first), this);
                AddDirectory(parent);
                var rest = name.Skip(1).Take(name.Length - 2);
                var queue = new Queue<string>(rest);

                foreach (var item in queue)
                {
                    var dir = new ZippedDirectory(DirectoryName.GetDirectoryName(parent.Name, item), parent);
                    parent.AddDirectory(dir);
                    parent = dir;
                }
                var file = name.Last();

                byte[] data = input.ReadToEnd();
                Trace.WriteLine("Read: " + data.Length + " bytes");
                //neds to be added
                var zipfile = new ZippedFile(FileName.GetFileName(parent.Name, file), data);
                parent.AddFile(zipfile);
            }
        }
        public List<UInt32> LoadSearchList(string filepath)
        {
            // spin while background writing to prevent us from reading a file that has yet to be written
            while (BackgroundWriting) ;

            ZipInputStream instream = new ZipInputStream(filepath);
            BinaryFormatter formatter = new BinaryFormatter();

            // First entry is the dump
            instream.GetNextEntry();

            // Second entry is the list
            instream.GetNextEntry();

            List<UInt32> searchList = (List<UInt32>)formatter.Deserialize(instream);

            instream.Close();
            instream.Dispose();
        
            return searchList;
        }
Example #26
0
        internal ZipPackage(Stream stream)
        {
            bool hasContentTypeXml = false;
            if (stream == null || stream.Length == 0)
            {
                AddNew();
            }
            else
            {
                var rels = new Dictionary<string, string>();
                stream.Seek(0, SeekOrigin.Begin);                
                using (ZipInputStream zip = new ZipInputStream(stream))
                {
                    var e = zip.GetNextEntry();
                    while (e != null)
                    {
                        if (e.UncompressedSize > 0)
                        {
                            var b = new byte[e.UncompressedSize];
                            var size = zip.Read(b, 0, (int)e.UncompressedSize);
                            if (e.FileName.Equals("[content_types].xml", StringComparison.InvariantCultureIgnoreCase))
                            {
                                AddContentTypes(Encoding.UTF8.GetString(b));
                                hasContentTypeXml = true;
                            }
                            else if (e.FileName.Equals("_rels/.rels", StringComparison.InvariantCultureIgnoreCase)) 
                            {
                                ReadRelation(Encoding.UTF8.GetString(b), "");
                            }
                            else
                            {
                                if (e.FileName.EndsWith(".rels", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    rels.Add(GetUriKey(e.FileName), Encoding.UTF8.GetString(b));
                                }
                                else
                                {
                                    var part = new ZipPackagePart(this, e);
                                    part.Stream = new MemoryStream();
                                    part.Stream.Write(b, 0, b.Length);
                                    Parts.Add(GetUriKey(e.FileName), part);
                                }
                            }
                        }
                        else
                        {
                        }
                        e = zip.GetNextEntry();
                    }

                    foreach (var p in Parts)
                    {
                        string name = Path.GetFileName(p.Key);
                        string extension = Path.GetExtension(p.Key);
                        string relFile = string.Format("{0}_rels/{1}.rels", p.Key.Substring(0, p.Key.Length - name.Length), name);
                        if (rels.ContainsKey(relFile))
                        {
                            p.Value.ReadRelation(rels[relFile], p.Value.Uri.OriginalString);
                        }
                        if (_contentTypes.ContainsKey(p.Key))
                        {
                            p.Value.ContentType = _contentTypes[p.Key].Name;
                        }
                        else if (extension.Length > 1 && _contentTypes.ContainsKey(extension.Substring(1)))
                        {
                            p.Value.ContentType = _contentTypes[extension.Substring(1)].Name;
                        }
                    }
                    if (!hasContentTypeXml)
                    {
                        throw (new InvalidDataException("The file is not an valid Package file. If the file is encrypted, please supply the password in the constructor."));
                    }
                    if (!hasContentTypeXml)
                    {
                        throw (new InvalidDataException("The file is not an valid Package file. If the file is encrypted, please supply the password in the constructor."));
                    }
                    zip.Close();
                }
            }
        }
        public Dump LoadSearchDump(string filepath)
        {
            // spin while background writing to prevent us from reading a file that has yet to be written
            while (BackgroundWriting) ;

            ZipInputStream instream = new ZipInputStream(filepath);
            BinaryFormatter formatter = new BinaryFormatter();

            // First entry is the dump
            instream.GetNextEntry();
            Dump searchDump = new Dump((uint)formatter.Deserialize(instream), (uint)formatter.Deserialize(instream));
            instream.Read(searchDump.mem, 0, (int)(searchDump.EndAddress - searchDump.StartAddress));

            instream.Close();
            instream.Dispose();

            return searchDump;
        }
Example #28
0
        public void UnpackFiles(Stream strm, Callbacks callbacks)
        {
            ZipEntry ze;
            ZipInputStream zstrm = new ZipInputStream(strm, true);
            List<FileEntry> results = new List<FileEntry>();

            SetupZIPParams();
            while (true)
            {
                ze = zstrm.GetNextEntry();
                if (ze == null)
                    break;

                if (ze.IsDirectory)
                    continue;

                byte[] data = new byte[ze.UncompressedSize];
                zstrm.Read(data, 0, (int)ze.UncompressedSize);
                callbacks.WriteData(ze.FileName, data);
            };
        }
 public ZipContainer(Object o)
 {
     _zf = (o as ZipFile);
     _zos = (o as ZipOutputStream);
     _zis = (o as ZipInputStream);
 }
Example #30
-1
 private void SetupW3Example()
 {
     Stream input = GetType().Assembly.GetManifestResourceStream(GetType().Namespace + ".w3example.zip");
     using(ZipInputStream z = new ZipInputStream(input))
     {
         ZipEntry e;
         while (null != (e = z.GetNextEntry()))
         {
             if (e.IsDirectory) continue;
             string output = Path.Combine(W3ExampleDirectory, e.FileName);
             Directory.CreateDirectory(Path.GetDirectoryName(output));
             File.WriteAllBytes(output, IOStream.Read(z, (int)e.UncompressedSize));
         }
     }
 }