Example #1
0
        public static void AddToZip(BackgroundWorker worker, string zipfile, string FileToAdd, string AsFilename = "", bool showProgress = true, Ionic.Zlib.CompressionLevel complevel = Ionic.Zlib.CompressionLevel.Default)
        {
            if (!File.Exists(zipfile))
                throw new FileNotFoundException("Zipfile " + zipfile + " does not exist");

            bool exists = ExistsInZip(zipfile, AsFilename == "" ? FileToAdd : AsFilename);
            using (ZipFile zip = new ZipFile(zipfile))
            {
                Utility.SetZipTempFolder(zip);
                zip.CompressionLevel = complevel;

                if (exists)
                    zip.RemoveEntry(AsFilename == "" ? FileToAdd : AsFilename);
                ZipEntry ze = zip.AddFile(FileToAdd, "");
                if (!string.IsNullOrEmpty(AsFilename))
                    ze.FileName = AsFilename;

                if (showProgress)
                    zip.SaveProgress += (o, e) =>
                    {
                        if (e.EventType == ZipProgressEventType.Saving_EntryBytesRead && e.CurrentEntry.FileName == (AsFilename == "" ? FileToAdd : AsFilename))
                            worker.ReportProgress((int)((float)e.BytesTransferred / e.TotalBytesToTransfer * 100));
                    };
                zip.Save();
            }
        }
Example #2
0
 public static void ZipFolder(string inputFolder, string outputFile, Ionic.Zlib.CompressionLevel level)
 {
     using (ZipFile zip = new ZipFile())
     {
         zip.CompressionLevel = level;
         zip.AddDirectory(inputFolder, "");
         //zip.AddFiles(GenerateFileList(inputFolder));
         //zip.AddDirectory(inputFolder);
         zip.Save(outputFile);
     }
 }
Example #3
0
        /// <summary>
        /// Retrieve the ZipEntry items in the ZipFile that conform to the specified criteria.
        /// </summary>
        /// <remarks>
        ///
        /// <para>
        /// This method applies the criteria set in the FileSelector instance (as described in
        /// the <see cref="FileSelector.SelectionCriteria"/>) to the specified ZipFile.  Using this
        /// method, for example, you can retrieve all entries from the given ZipFile that
        /// have filenames ending in .txt.
        /// </para>
        ///
        /// <para>
        /// Normally, applications would not call this method directly.  This method is used
        /// by the ZipFile class.
        /// </para>
        ///
        /// <para>
        /// Using the appropriate SelectionCriteria, you can retrieve entries based on size,
        /// time, and attributes. See <see cref="FileSelector.SelectionCriteria"/> for a
        /// description of the syntax of the SelectionCriteria string.
        /// </para>
        ///
        /// </remarks>
        ///
        /// <param name="zip">The ZipFile from which to retrieve entries.</param>
        ///
        /// <returns>a collection of ZipEntry objects that conform to the criteria.</returns>
        public ICollection<Ionic.Zip.ZipEntry> SelectEntries(Ionic.Zip.ZipFile zip)
        {
            var list = new List<Ionic.Zip.ZipEntry>();

            foreach (Ionic.Zip.ZipEntry e in zip)
            {
                if (this.Evaluate(e))
                    list.Add(e);
            }

            return list;
        }
Example #4
0
 public void FillKnowledge(CandidateViewModel candidate)
 {
     _driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
     Ionic.EnterText(candidate.Ionic.ToString());
     Android.EnterText(candidate.Android.ToString());
     Angular.EnterText(candidate.Angular.ToString());
     Asp.EnterText(candidate.Asp.ToString());
     Others.EnterText(candidate.Others);
     Photoshop.EnterText(candidate.Photoshop.ToString());
     Illustrator.EnterText(candidate.Illustrator.ToString());
     Html.EnterText(candidate.Html.ToString());
     Jquery.EnterText(candidate.Jquery.ToString());
 }
            public WorkItem(int size, Ionic.Zlib.CompressionLevel compressLevel, CompressionStrategy strategy)
            {
                buffer= new byte[size];
                // alloc 5 bytes overhead for every block (margin of safety= 2)
                int n = size + ((size / 32768)+1) * 5 * 2;
                compressed= new byte[n];

                status = (int)Status.None;
                compressor = new ZlibCodec();
                compressor.InitializeDeflate(compressLevel, false);
                compressor.OutputBuffer = compressed;
                compressor.InputBuffer = buffer;
            }
Example #6
0
        internal void FinishOutputStream(Stream s,
                                         CountingStream entryCounter,
                                         Stream encryptor,
                                         Stream compressor,
                                         Ionic.Crc.CrcCalculatorStream output)
        {
            if (output == null) return;

            output.Close();

            // by calling Close() on the deflate stream, we write the footer bytes, as necessary.
            if ((compressor as Ionic.Zlib.DeflateStream) != null)
                compressor.Close();
            #if BZIP
            else if ((compressor as Ionic.BZip2.BZip2OutputStream) != null)
                compressor.Close();
            #if !NETCF
            else if ((compressor as Ionic.BZip2.ParallelBZip2OutputStream) != null)
                compressor.Close();
            #endif
            #endif

            #if !NETCF
            else if ((compressor as Ionic.Zlib.ParallelDeflateOutputStream) != null)
                compressor.Close();
            #endif

            encryptor.Flush();
            encryptor.Close();

            _LengthOfTrailer = 0;

            _UncompressedSize = output.TotalBytesSlurped;

            #if AESCRYPTO
            WinZipAesCipherStream wzacs = encryptor as WinZipAesCipherStream;
            if (wzacs != null && _UncompressedSize > 0)
            {
                s.Write(wzacs.FinalAuthentication, 0, 10);
                _LengthOfTrailer += 10;
            }
            #endif
            _CompressedFileDataSize = entryCounter.BytesWritten;
            _CompressedSize = _CompressedFileDataSize;   // may be adjusted
            _Crc32 = output.Crc;

            // Set _RelativeOffsetOfLocalHeader now, to allow for re-streaming
            StoreRelativeOffset();
        }
 public WorkItem(int size,
                 Ionic.Zlib.CompressionLevel compressLevel,
                 CompressionStrategy strategy,
                 int ix)
 {
     this.buffer= new byte[size];
     // alloc 5 bytes overhead for every block (margin of safety= 2)
     int n = size + ((size / 32768)+1) * 5 * 2;
     this.compressed = new byte[n];
     this.compressor = new ZlibCodec();
     this.compressor.InitializeDeflate(compressLevel, false);
     this.compressor.OutputBuffer = this.compressed;
     this.compressor.InputBuffer = this.buffer;
     this.index = ix;
 }
Example #8
0
 private static void RecursiveArchivate(string path, Ionic.Zip.ZipFile zip, string relPath, ref DateTime dt)
 {
     foreach (var file in Directory.GetFiles(path))
     {
         //if (!CheckFile(file)) continue;
         var fdt = File.GetLastWriteTime(file);
         if (fdt > dt) dt = File.GetLastWriteTime(file);
         zip.AddFile(file, relPath);
     }
     foreach (string directory in Directory.GetDirectories(path))
     {
         var dirName = new DirectoryInfo(directory).Name;
         RecursiveArchivate(directory, zip, string.Format(@"{0}\{1}", relPath, dirName), ref dt);
     }
 }
Example #9
0
 internal override bool Evaluate(Ionic.Zip.ZipEntry entry)
 {
     bool result = Left.Evaluate(entry);
     switch (Conjunction)
     {
         case LogicalConjunction.AND:
             if (result)
                 result = Right.Evaluate(entry);
             break;
         case LogicalConjunction.OR:
             if (!result)
                 result = Right.Evaluate(entry);
             break;
         case LogicalConjunction.XOR:
             result ^= Right.Evaluate(entry);
             break;
     }
     return result;
 }
Example #10
0
        void LNSF_SaveProgress(object sender, Ionic.Zip.SaveProgressEventArgs e)
        {
            switch (e.EventType)
            {
                case ZipProgressEventType.Saving_Started:
                    _numEntriesSaved = 0;
                    _txrx.Send("status saving started...");
                    _pb1Set = false;
                    break;

                case ZipProgressEventType.Saving_BeforeWriteEntry:
                    _numEntriesSaved++;
                    if (_numEntriesSaved % 64 == 0)
                        _txrx.Send(String.Format("status Compressing {0}", e.CurrentEntry.FileName));
                    if (!_pb1Set)
                    {
                        _txrx.Send(String.Format("pb 1 max {0}", e.EntriesTotal));
                        _pb1Set = true;
                    }
                    break;

                case ZipProgressEventType.Saving_EntryBytesRead:
                    Assert.IsTrue(e.BytesTransferred <= e.TotalBytesToTransfer);
                    break;

                case ZipProgressEventType.Saving_AfterWriteEntry:
                    _txrx.Send("pb 1 step");
                    break;

                case ZipProgressEventType.Saving_Completed:
                    _txrx.Send("status Save completed");
                    _pb1Set = false;
                    _txrx.Send("pb 1 max 1");
                    _txrx.Send("pb 1 value 1");
                    break;
            }
        }
 internal override bool Evaluate(Ionic.Zip.ZipEntry entry)
 {
     FileAttributes fileAttrs = entry.Attributes;
     return _Evaluate(fileAttrs);
 }
        internal override bool Evaluate(Ionic.Zip.ZipEntry entry)
        {
            bool result = (ObjectType == 'D')
                ? entry.IsDirectory
                : !entry.IsDirectory;

            if (Operator != ComparisonOperator.EqualTo)
                result = !result;
            return result;
        }
 internal override bool Evaluate(Ionic.Zip.ZipEntry entry)
 {
     DateTime x;
     switch (Which)
     {
         case WhichTime.atime:
             x = entry.AccessedTime;
             break;
         case WhichTime.mtime:
             x = entry.ModifiedTime;
             break;
         case WhichTime.ctime:
             x = entry.CreationTime;
             break;
         default: throw new ArgumentException("??time");
     }
     return _Evaluate(x);
 }
 internal override bool Evaluate(Ionic.Zip.ZipEntry entry)
 {
     return _Evaluate(entry.UncompressedSize);
 }
        internal override bool Evaluate(Ionic.Zip.ZipEntry entry)
        {
            // swap forward slashes in the entry.FileName for backslashes
            string transformedFileName = entry.FileName.Replace("/", "\\");

            return _Evaluate(transformedFileName);
        }
Example #16
0
        void _Zip64_Over65534Entries(Zip64Option z64option,
                                            EncryptionAlgorithm encryption,
                                            Ionic.Zlib.CompressionLevel compression)
        {
            // Emitting a zip file with > 65534 entries requires the use of ZIP64 in
            // the central directory.
            int numTotalEntries = _rnd.Next(4616)+65534;
            //int numTotalEntries = _rnd.Next(461)+6534;
            //int numTotalEntries = _rnd.Next(46)+653;
            string enc = encryption.ToString();
            if (enc.StartsWith("WinZip")) enc = enc.Substring(6);
            else if (enc.StartsWith("Pkzip")) enc = enc.Substring(0,5);
            string zipFileToCreate = String.Format("Zip64.ZF_Over65534.{0}.{1}.{2}.zip",
                                                   z64option.ToString(),
                                                   enc,
                                                   compression.ToString());

            _testTitle = String.Format("ZipFile #{0} 64({1}) E({2}), C({3})",
                                       numTotalEntries,
                                       z64option.ToString(),
                                       enc,
                                       compression.ToString());
            _txrx = TestUtilities.StartProgressMonitor(zipFileToCreate,
                                                       _testTitle,
                                                       "starting up...");

            _txrx.Send("pb 0 max 4"); // 3 stages: AddEntry, Save, Verify
            _txrx.Send("pb 0 value 0");

            string password = Path.GetRandomFileName();

            string statusString = String.Format("status Encrypt:{0} Compress:{1}...",
                                                enc,
                                                compression.ToString());

            int numSaved = 0;
            var saveProgress = new EventHandler<SaveProgressEventArgs>( (sender, e) => {
                    switch (e.EventType)
                    {
                        case ZipProgressEventType.Saving_Started:
                        _txrx.Send("status saving...");
                        _txrx.Send("pb 1 max " + numTotalEntries);
                        numSaved= 0;
                        break;

                        case ZipProgressEventType.Saving_AfterWriteEntry:
                        numSaved++;
                        if ((numSaved % 128) == 0)
                        {
                            _txrx.Send("pb 1 value " + numSaved);
                            _txrx.Send(String.Format("status Saving entry {0}/{1} ({2:N0}%)",
                                                     numSaved, numTotalEntries,
                                                     numSaved / (0.01 * numTotalEntries)
                                                     ));
                        }
                        break;

                        case ZipProgressEventType.Saving_Completed:
                        _txrx.Send("status Save completed");
                        _txrx.Send("pb 1 max 1");
                        _txrx.Send("pb 1 value 1");
                        break;
                    }
                });

            string contentFormatString =
                "This is the content for entry #{0}.\r\n\r\n" +
                "AAAAAAA BBBBBB AAAAA BBBBB AAAAA BBBBB AAAAA\r\n"+
                "AAAAAAA BBBBBB AAAAA BBBBB AAAAA BBBBB AAAAA\r\n";
            _txrx.Send(statusString);
            int dirCount= 0;
            using (var zip = new ZipFile())
            {
                _txrx.Send(String.Format("pb 1 max {0}", numTotalEntries));
                _txrx.Send("pb 1 value 0");

                zip.Password = password;
                zip.Encryption = encryption;
                zip.CompressionLevel = compression;
                zip.SaveProgress += saveProgress;
                zip.UseZip64WhenSaving = z64option;
                // save space when saving the file:
                zip.EmitTimesInWindowsFormatWhenSaving = false;
                zip.EmitTimesInUnixFormatWhenSaving = false;

                // add files:
                for (int m=0; m<numTotalEntries; m++)
                {
                    if (_rnd.Next(7)==0)
                    {
                        string entryName = String.Format("{0:D5}", m);
                        zip.AddDirectoryByName(entryName);
                        dirCount++;
                    }
                    else
                    {
                        string entryName = String.Format("{0:D5}.txt", m);
                        if (_rnd.Next(12)==0)
                        {
                            string contentBuffer = String.Format(contentFormatString, m);
                            byte[] buffer = System.Text.Encoding.ASCII.GetBytes(contentBuffer);
                            zip.AddEntry(entryName, contentBuffer);
                        }
                        else
                            zip.AddEntry(entryName, Stream.Null);
                    }

                    if (m % 1024 == 0)
                    {
                        _txrx.Send("pb 1 value " + m);
                        string msg = String.Format("status adding entry {0}/{1}  ({2:N0}%)",
                                            m, numTotalEntries, (m/(0.01*numTotalEntries)));
                        _txrx.Send(msg);
                    }
                }

                _txrx.Send("pb 0 step");
                _txrx.Send(statusString + " Saving...");
                zip.Save(zipFileToCreate);
            }

            _txrx.Send("pb 0 step");
            _txrx.Send("pb 1 value 0");
            _txrx.Send("status Reading...");

            // verify the zip by unpacking.
            _numFilesToExtract = numTotalEntries;
            _numExtracted= 1;
            _pb1Set = false;
            verb = "verify";
            BasicVerifyZip(zipFileToCreate, password, false, Zip64ExtractProgress);

            _txrx.Send("pb 0 step");
            _txrx.Send("status successful extract, now doing final count...");
            _txrx.Send("pb 1 value 0");
            Assert.AreEqual<int>(numTotalEntries-dirCount,
                                 TestUtilities.CountEntries(zipFileToCreate));
            _txrx.Send("pb 0 step");
        }
Example #17
0
 public static void SetZipTempFolder(Ionic.Zip.ZipFile zf)
 {
     if (!string.IsNullOrEmpty(Settings.templocation))
         zf.TempFileFolder = Settings.templocation;
 }
 public override void PackResources(Ionic.Zip.ZipFile zip, String archiveTargetPath, IPath sourcePath)
 {
     RelativePath path = new RelativePath(this.Source, sourcePath);
     zip.AddFile(path.AbsolutePath, archiveTargetPath);
 }
 private bool Evaluate(Ionic.Zip.ZipEntry entry)
 {
     bool result = _Criterion.Evaluate(entry);
     return result;
 }
Example #20
0
        /// <summary>
        ///   Prepare the given stream for output - wrap it in a CountingStream, and
        ///   then in a CRC stream, and an encryptor and deflator as appropriate.
        /// </summary>
        /// <remarks>
        ///   <para>
        ///     Previously this was used in ZipEntry.Write(), but in an effort to
        ///     introduce some efficiencies in that method I've refactored to put the
        ///     code inline.  This method still gets called by ZipOutputStream.
        ///   </para>
        /// </remarks>
        internal void PrepOutputStream(Stream s,
                                       long streamLength,
                                       out CountingStream outputCounter,
                                       out Stream encryptor,
                                       out Stream compressor,
                                       out Ionic.Crc.CrcCalculatorStream output)
        {
            TraceWriteLine("PrepOutputStream: e({0}) comp({1}) crypto({2}) zf({3})",
                           FileName,
                           CompressionLevel,
                           Encryption,
                           _container.Name);

            // Wrap a counting stream around the raw output stream:
            // This is the last thing that happens before the bits go to the
            // application-provided stream.
            outputCounter = new CountingStream(s);

            // Sometimes the incoming "raw" output stream is already a CountingStream.
            // Doesn't matter. Wrap it with a counter anyway. We need to count at both
            // levels.

            if (streamLength != 0L)
            {
                // Maybe wrap an encrypting stream around that:
                // This will happen BEFORE output counting, and AFTER deflation, if encryption
                // is used.
                encryptor = MaybeApplyEncryption(outputCounter);

                // Maybe wrap a compressing Stream around that.
                // This will happen BEFORE encryption (if any) as we write data out.
                compressor = MaybeApplyCompression(encryptor, streamLength);
            }
            else
            {
                encryptor = compressor = outputCounter;
            }
            // Wrap a CrcCalculatorStream around that.
            // This will happen BEFORE compression (if any) as we write data out.
            output = new Ionic.Crc.CrcCalculatorStream(compressor, true);
        }
Example #21
0
        private void Transaction_ProgressChanged(object sender, Ionic.Zip.SaveProgressEventArgs e)
        {
            try
            {
                if (prbMaster == null || prbSlave == null ||
                    prbMaster.IsDisposed || prbSlave.IsDisposed ||
                    !prbMaster.IsHandleCreated || !prbSlave.IsHandleCreated ||
                    !prbMaster.Created || !prbSlave.Created)
                    return;

                if (e.TotalBytesToTransfer > 0)
                {
                    if (this.prbSlave.InvokeRequired)
                    {
                        this.prbSlave.Invoke(new Action(delegate
                        {
                            this.prbSlave.Value = unchecked((int)(e.BytesTransferred * 100 / e.TotalBytesToTransfer));
                        }));
                    }
                }
                if (e.EntriesSaved > 0 && e.EntriesTotal > 0)
                {
                    if (this.prbMaster.InvokeRequired)
                    {
                        this.prbMaster.Invoke(new Action(delegate
                        {
                            this.prbMaster.Value = unchecked((int)((double)e.EntriesSaved * 100 / (double)e.EntriesTotal));
                        }));
                    }
                }
            }
            catch (Exception ex) { EventReflector.CallReport.Post(new ReportEventArgs("GUI.TransferToDisk_ProgressChanged", ex)); }
        }
        /// <summary>
        /// Retrieve the ZipEntry items in the ZipFile that conform to the specified criteria.
        /// </summary>
        /// <remarks>
        ///
        /// <para>
        /// This method applies the criteria set in the FileSelector instance (as described in
        /// the <see cref="FileSelector.SelectionCriteria"/>) to the specified ZipFile.  Using this
        /// method, for example, you can retrieve all entries from the given ZipFile that
        /// have filenames ending in .txt.
        /// </para>
        ///
        /// <para>
        /// Normally, applications would not call this method directly.  This method is used
        /// by the ZipFile class.
        /// </para>
        ///
        /// <para>
        /// This overload allows the selection of ZipEntry instances from the ZipFile to be restricted
        /// to entries contained within a particular directory in the ZipFile.
        /// </para>
        ///
        /// <para>
        /// Using the appropriate SelectionCriteria, you can retrieve entries based on size,
        /// time, and attributes. See <see cref="FileSelector.SelectionCriteria"/> for a
        /// description of the syntax of the SelectionCriteria string.
        /// </para>
        ///
        /// </remarks>
        ///
        /// <param name="zip">The ZipFile from which to retrieve entries.</param>
        ///
        /// <param name="directoryPathInArchive">
        /// the directory in the archive from which to select entries. If null, then
        /// all directories in the archive are used.
        /// </param>
        ///
        /// <returns>a collection of ZipEntry objects that conform to the criteria.</returns>
        public ICollection<Ionic.Zip.ZipEntry> SelectEntries(Ionic.Zip.ZipFile zip, string directoryPathInArchive)
        {
            var list = new List<Ionic.Zip.ZipEntry>();
            // workitem 8559
            string slashSwapped = (directoryPathInArchive==null) ? null : directoryPathInArchive.Replace("/","\\");
            // workitem 9174
            if (slashSwapped != null)
            {
                while (slashSwapped.EndsWith("\\"))
                    slashSwapped= slashSwapped.Substring(0, slashSwapped.Length-1);
            }
            foreach (Ionic.Zip.ZipEntry e in zip)
            {
                if (directoryPathInArchive == null || (Path.GetDirectoryName(e.FileName) == directoryPathInArchive)
                    || (Path.GetDirectoryName(e.FileName) == slashSwapped)) // workitem 8559
                    if (this.Evaluate(e))
                        list.Add(e);
            }

            return list;
        }
 public override void PackResources(Ionic.Zip.ZipFile zip, String archiveTargetPath, ScriptCenter.Utils.IPath sourcePath)
 {
     //No resources to pack for this action.
 }
 public void SetCompression(Ionic.Zlib.CompressionLevel Level)
 {
     Zip.CompressionLevel = Level;
 }
        internal override bool Evaluate(Ionic.Zip.ZipEntry entry)
        {
            // swap slashes in reference to local configuration
            string transformedFileName = entry.FileName.Replace(Path.DirectorySeparatorChar == '/' ? '\\' : '/', Path.DirectorySeparatorChar);

            return _Evaluate(transformedFileName);
        }
Example #26
0
        private void _ZOS_z64Over65534Entries
            (Zip64Option z64option,
             EncryptionAlgorithm encryption,
             Ionic.Zlib.CompressionLevel compression)
        {
            TestContext.WriteLine("_ZOS_z64Over65534Entries hello: {0}",
                                  DateTime.Now.ToString("G"));
            int fileCount = _rnd.Next(14616) + 65536;
            //int fileCount = _rnd.Next(146) + 5536;
            TestContext.WriteLine("entries: {0}", fileCount);
            var txrxLabel =
                String.Format("ZOS  #{0} 64({3}) E({1}) C({2})",
                              fileCount,
                              encryption.ToString(),
                              compression.ToString(),
                              z64option.ToString());

            TestContext.WriteLine("label: {0}", txrxLabel);
            string zipFileToCreate =
                String.Format("ZOS.Zip64.over65534.{0}.{1}.{2}.zip",
                              z64option.ToString(), encryption.ToString(),
                              compression.ToString());

            TestContext.WriteLine("zipFileToCreate: {0}", zipFileToCreate);

            _txrx = TestUtilities.StartProgressMonitor(zipFileToCreate,
                                                       txrxLabel, "starting up...");

            TestContext.WriteLine("generating {0} entries ", fileCount);
            _txrx.Send("pb 0 max 3"); // 2 stages: Write, Count, Verify
            _txrx.Send("pb 0 value 0");

            string password = Path.GetRandomFileName();

            string statusString = String.Format("status Encryption:{0} Compression:{1}",
                                                encryption.ToString(),
                                                compression.ToString());

            _txrx.Send(statusString);

            int dirCount = 0;

            using (FileStream fs = File.Create(zipFileToCreate))
            {
                using (var output = new ZipOutputStream(fs))
                {
                    _txrx.Send("test " + txrxLabel);
                    System.Threading.Thread.Sleep(400);
                    _txrx.Send("pb 1 max " + fileCount);
                    _txrx.Send("pb 1 value 0");

                    output.Password = password;
                    output.Encryption = encryption;
                    output.CompressionLevel = compression;
                    output.EnableZip64 = z64option;
                    for (int k = 0; k < fileCount; k++)
                    {
                        if (_rnd.Next(7) == 0)
                        {
                            // make it a directory
                            string entryName = String.Format("{0:D4}/", k);
                            output.PutNextEntry(entryName);
                            dirCount++;
                        }
                        else
                        {
                            string entryName = String.Format("{0:D4}.txt", k);
                            output.PutNextEntry(entryName);

                            // only a few entries are non-empty
                            if (_rnd.Next(18) == 0)
                            {
                                var block = TestUtilities.GenerateRandomAsciiString();
                                string content = String.Format("This is the content for entry #{0}.\n", k);
                                int n = _rnd.Next(4) + 1;
                                for (int j=0; j < n; j++)
                                    content+= block;

                                byte[] buffer = System.Text.Encoding.ASCII.GetBytes(content);
                                output.Write(buffer, 0, buffer.Length);
                            }
                        }
                        if (k % 1024 == 0)
                            _txrx.Send(String.Format("status saving ({0}/{1}) {2:N0}%",
                                                     k, fileCount,
                                                     ((double)k) / (0.01 * fileCount)));
                        else if (k % 256 == 0)
                            _txrx.Send("pb 1 value " + k);
                    }
                }
            }

            _txrx.Send("pb 1 max 1");
            _txrx.Send("pb 1 value 1");
            _txrx.Send("pb 0 step");

            System.Threading.Thread.Sleep(400);

            TestContext.WriteLine("Counting entries ... " + DateTime.Now.ToString("G"));
            _txrx.Send("status Counting entries...");
            Assert.AreEqual<int>
                (fileCount - dirCount,
                 TestUtilities.CountEntries(zipFileToCreate),
                 "{0}: The zip file created has the wrong number of entries.",
                 zipFileToCreate);
            _txrx.Send("pb 0 step");
            System.Threading.Thread.Sleep(140);

            // basic verify. The output is really large, so we pass emitOutput=false .
            _txrx.Send("status Verifying...");
            TestContext.WriteLine("Verifying ... " + DateTime.Now.ToString("G"));
            _numExtracted = 0;
            _numFilesToExtract = fileCount;
            _txrx.Send("pb 1 max " + fileCount);
            System.Threading.Thread.Sleep(200);
            _txrx.Send("pb 1 value 0");
            BasicVerifyZip(zipFileToCreate, password, false, Streams_ExtractProgress);
            _txrx.Send("pb 0 step");
            System.Threading.Thread.Sleep(800);
            TestContext.WriteLine("Done ... " + DateTime.Now.ToString("G"));
        }
        /// <summary>
        /// Retrieve the ZipEntry items in the ZipFile that conform to the specified criteria.
        /// </summary>
        /// <remarks>
        ///
        /// <para>
        /// This method applies the criteria set in the FileSelector instance (as described in
        /// the <see cref="FileSelector.SelectionCriteria"/>) to the specified ZipFile.  Using this
        /// method, for example, you can retrieve all entries from the given ZipFile that
        /// have filenames ending in .txt.
        /// </para>
        ///
        /// <para>
        /// Normally, applications would not call this method directly.  This method is used
        /// by the ZipFile class.
        /// </para>
        ///
        /// <para>
        /// Using the appropriate SelectionCriteria, you can retrieve entries based on size,
        /// time, and attributes. See <see cref="FileSelector.SelectionCriteria"/> for a
        /// description of the syntax of the SelectionCriteria string.
        /// </para>
        ///
        /// </remarks>
        ///
        /// <param name="zip">The ZipFile from which to retrieve entries.</param>
        ///
        /// <returns>a collection of ZipEntry objects that conform to the criteria.</returns>
        public ICollection<Ionic.Zip.ZipEntry> SelectEntries(Ionic.Zip.ZipFile zip)
        {
            if (zip == null)
                throw new ArgumentNullException("zip");

            var list = new List<Ionic.Zip.ZipEntry>();

            foreach (Ionic.Zip.ZipEntry e in zip)
            {
                if (this.Evaluate(e))
                    list.Add(e);
            }

            return list;
        }
Example #28
0
 void ReadZip(Ionic.Zip.ZipFile archive, DirectoryInfo dinfo)
 {
     foreach (Ionic.Zip.ZipEntry entry in archive)
         entry.Extract(dinfo.FullName);
 }
 private static int GetFileFormatByZip(Ionic.Zip.ZipFile oZipFile)
 {
     
     if (oZipFile.ContainsEntry("[Content_Types].xml"))
     {
         Ionic.Zip.ZipEntry oEntry = oZipFile["[Content_Types].xml"];
         using (MemoryStream oMemoryStream = new MemoryStream((int)oEntry.UncompressedSize))
         {
             oEntry.Extract(oMemoryStream);
             oMemoryStream.Position = 0;
             string sContent = System.Text.UTF8Encoding.UTF8.GetString(oMemoryStream.GetBuffer(), 0, (int)oMemoryStream.Length);
             if (-1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml") ||
                 -1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml") ||
                 -1 != sContent.IndexOf("application/vnd.ms-word.document.macroEnabled.main+xml") ||
                 -1 != sContent.IndexOf("application/vnd.ms-word.template.macroEnabledTemplate.main+xml"))
                 return FileFormats.AVS_OFFICESTUDIO_FILE_DOCUMENT_DOCX;
             else if (-1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml") ||
                 -1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml") ||
                 -1 != sContent.IndexOf("application/vnd.ms-excel.sheet.macroEnabled.main+xml") ||
                 -1 != sContent.IndexOf("application/vnd.ms-excel.template.macroEnabled.main+xml"))
                 return FileFormats.AVS_OFFICESTUDIO_FILE_SPREADSHEET_XLSX;
             else if (-1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml") ||
                 -1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.presentationml.template.main+xml") ||
                 -1 != sContent.IndexOf("application/vnd.ms-powerpoint.presentation.macroEnabled.main+xml") ||
                 -1 != sContent.IndexOf("application/vnd.ms-powerpoint.slideshow.macroEnabled.main+xml") ||
                 -1 != sContent.IndexOf("application/vnd.ms-powerpoint.template.macroEnabled.main+xml"))
                 return FileFormats.AVS_OFFICESTUDIO_FILE_PRESENTATION_PPTX;
             else if (-1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml"))
                 return FileFormats.AVS_OFFICESTUDIO_FILE_PRESENTATION_PPSX;
         }
     }
     if (oZipFile.ContainsEntry("mimetype"))
     {
         Ionic.Zip.ZipEntry oEntry = oZipFile["mimetype"];
         using (MemoryStream oMemoryStream = new MemoryStream((int)oEntry.UncompressedSize))
         {
             oEntry.Extract(oMemoryStream);
             oMemoryStream.Position = 0;
             string sContent = System.Text.ASCIIEncoding.ASCII.GetString(oMemoryStream.GetBuffer(), 0, (int)oMemoryStream.Length);
             if (-1 != sContent.IndexOf("application/vnd.oasis.opendocument.text"))
                 return FileFormats.AVS_OFFICESTUDIO_FILE_DOCUMENT_ODT;
             else if (-1 != sContent.IndexOf("application/vnd.oasis.opendocument.spreadsheet"))
                 return FileFormats.AVS_OFFICESTUDIO_FILE_SPREADSHEET_ODS;
             else if (-1 != sContent.IndexOf("application/vnd.oasis.opendocument.presentation"))
                 return FileFormats.AVS_OFFICESTUDIO_FILE_PRESENTATION_ODP;
             else if (-1 != sContent.IndexOf("application/epub+zip"))
                 return FileFormats.AVS_OFFICESTUDIO_FILE_DOCUMENT_EPUB;
         }
     }
     if (oZipFile.ContainsEntry("_rels/.rels"))
     {
         Ionic.Zip.ZipEntry oEntry = oZipFile["_rels/.rels"];
         using (MemoryStream oMemoryStream = new MemoryStream((int)oEntry.UncompressedSize))
         {
             oEntry.Extract(oMemoryStream);
             oMemoryStream.Position = 0;
             string sContent = System.Text.ASCIIEncoding.ASCII.GetString(oMemoryStream.GetBuffer(), 0, (int)oMemoryStream.Length);
             if (-1 != sContent.IndexOf("http://schemas.microsoft.com/xps/2005/06/fixedrepresentation"))
                 return FileFormats.AVS_OFFICESTUDIO_FILE_CROSSPLATFORM_XPS;
         }
     }
     
     if (oZipFile.ContainsEntry("_rels/.rels/[0].piece"))
         return FileFormats.AVS_OFFICESTUDIO_FILE_CROSSPLATFORM_XPS;
     if (oZipFile.ContainsEntry("Editor.bin"))
     {
         Ionic.Zip.ZipEntry oEntry = oZipFile["Editor.bin"];
         int nFormat = FileFormats.AVS_OFFICESTUDIO_FILE_UNKNOWN;
         using (MemoryStream oMemoryStream = new MemoryStream((int)oEntry.UncompressedSize))
         {
             oEntry.Extract(oMemoryStream);
             oMemoryStream.Position = 0;
             int nSignatureLength = 4;
             if (oMemoryStream.Length >= nSignatureLength)
             {
                 byte[] aSignature = new byte[nSignatureLength];
                 oMemoryStream.Read(aSignature, 0, nSignatureLength);
                 string sSignature = System.Text.ASCIIEncoding.ASCII.GetString(aSignature);
                 switch (sSignature)
                 {
                     case "DOCY": nFormat = FileFormats.AVS_OFFICESTUDIO_FILE_TEAMLAB_DOCY; break;
                     case "XLSY": nFormat = FileFormats.AVS_OFFICESTUDIO_FILE_TEAMLAB_XLSY; break;
                     case "PPTY": nFormat = FileFormats.AVS_OFFICESTUDIO_FILE_TEAMLAB_PPTY; break;
                 }
             }
         }
         if(FileFormats.AVS_OFFICESTUDIO_FILE_UNKNOWN != nFormat)
             return nFormat;
     }
     else if (oZipFile.ContainsEntry("Editor.xml"))
     {
         return FileFormats.AVS_OFFICESTUDIO_FILE_OTHER_OLD_PRESENTATION;
     }
     else if (oZipFile.ContainsEntry("Editor.svg"))
     {
         return FileFormats.AVS_OFFICESTUDIO_FILE_OTHER_OLD_DRAWING;
     }
     else if (oZipFile.ContainsEntry("Editor.html.arch"))
     {
         return FileFormats.AVS_OFFICESTUDIO_FILE_OTHER_OLD_DOCUMENT;
     }
     return FileFormats.AVS_OFFICESTUDIO_FILE_UNKNOWN;
 }
Example #30
0
 private static IEnumerable<string> ReadZipEntry(Ionic.Zip.ZipEntry entry)
 {
     using (var entryReader = new StreamReader(entry.OpenReader()))
     {
         while (!entryReader.EndOfStream)
         {
             yield return entryReader.ReadLine();
         }
     }
 }
 internal abstract bool Evaluate(Ionic.Zip.ZipEntry entry);