Write() public method

Write the data from the buffer to the stream.
As the application writes data into this stream, the data may be compressed and encrypted before being written out to the underlying stream, depending on the settings of the CompressionLevel and the Encryption properties.
public Write ( byte buffer, int offset, int count ) : void
buffer byte The buffer holding data to write to the stream.
offset int the offset within that data array to find the first byte to write.
count int the number of bytes to write.
return void
Example #1
0
 /********************************************************
 * CLASS METHODS
 *********************************************************/
 /// <summary>
 /// 
 /// </summary>
 /// <param name="zipPath"></param>
 /// <param name="filenamesAndData"></param>
 /// <returns></returns>
 public static bool Zip(string zipPath, System.Collections.Generic.Dictionary<string, string> filenamesAndData)
 {
     var success = true;
     var buffer = new byte[4096];
     try
     {
         using (var stream = new ZipOutputStream(System.IO.File.Create(zipPath)))
         {
             foreach (var filename in filenamesAndData.Keys)
             {
                 var file = filenamesAndData[filename].GetBytes();
                 var entry = stream.PutNextEntry(filename);
                 using (var ms = new System.IO.MemoryStream(file))
                 {
                     int sourceBytes;
                     do
                     {
                         sourceBytes = ms.Read(buffer, 0, buffer.Length);
                         stream.Write(buffer, 0, sourceBytes);
                     }
                     while (sourceBytes > 0);
                 }
             }
             stream.Flush();
             stream.Close();
         }
     }
     catch (System.Exception err)
     {
         System.Console.WriteLine("Compression.ZipData(): " + err.Message);
         success = false;
     }
     return success;
 }
Example #2
0
		public int Compress(PointCloudTile tile, byte[] uncompressedBuffer, int count, byte[] compressedBuffer)
		{
			MemorableMemoryStream compressedStream = new MemorableMemoryStream(compressedBuffer);

			using (ZipOutputStream zipStream = new ZipOutputStream(compressedStream, true))
			{
				zipStream.CompressionMethod = Ionic.Zip.CompressionMethod.Deflate;
				zipStream.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed;

				zipStream.PutNextEntry("a");
				zipStream.Write(uncompressedBuffer, 0, count);
			}

			return (int)compressedStream.MaxPosition;
		}
        public void WriteCompressedZip(string filepath)
        {
            ZipOutputStream outstream = new ZipOutputStream(filepath);
            outstream.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed;
            BinaryFormatter formatter = new BinaryFormatter();
            outstream.PutNextEntry("dump");

            //Logger.WriteLineTimed("Started compressing search dump");
            DateTime startTime = DateTime.Now;

            formatter.Serialize(outstream, searchDump.StartAddress);
            formatter.Serialize(outstream, searchDump.EndAddress);
            outstream.Write(searchDump.mem, 0, (int)(searchDump.EndAddress - searchDump.StartAddress));

            DateTime endTime = DateTime.Now;
            //Logger.WriteLineTimed("Finished compressing search dump in " + (new TimeSpan(endTime.Ticks - startTime.Ticks).TotalSeconds));

            outstream.PutNextEntry("list");

            //Logger.WriteLineTimed("Started copying search list");
            startTime = DateTime.Now;

            List<UInt32> copy = new List<uint>(resultsList);

            endTime = DateTime.Now;
            //Logger.WriteLineTimed("Finished copying search list in " + (new TimeSpan(endTime.Ticks - startTime.Ticks).TotalSeconds));

            //Logger.WriteLineTimed("Started compressing search list");
            startTime = DateTime.Now;

            formatter.Serialize(outstream, resultsList);

            endTime = DateTime.Now;
            //Logger.WriteLineTimed("Finished compressing search list in " + (new TimeSpan(endTime.Ticks - startTime.Ticks).TotalSeconds));

            outstream.Close();
            outstream.Dispose();
        }
Example #4
0
        public static void Save(string filePath)
        {
            //Get as xml
            XElement xml = Instance.GetAsXML();

            XElement directoryXml = new XElement("directory");

            //Save to location
            using (var fs = File.Create(filePath))
            {
                using (ZipOutputStream s = new ZipOutputStream(fs))
                {
                    s.PutNextEntry("ProjectInfo");
                    byte[] bytes = Encoding.ASCII.GetBytes(xml.ToString());
                    s.Write(bytes, 0, bytes.Length);

                    for (int i = 0; i < Instance.Files.Count; i++)
                    {
                        s.PutNextEntry(Instance.Files[i].GetXMLPath());
                        bytes = Instance.Files[i].GetAsBytes();
                        s.Write(bytes, 0, bytes.Length);

                        XElement fileElement = new XElement("File");
                        fileElement.Add(new XAttribute("ID", Instance.Files[i].GetXMLName()));
                        fileElement.Add(new XAttribute("Path", Instance.Files[i].GetXMLPath()));
                        directoryXml.Add(fileElement);
                    }

                    foreach (RomItem item in Instance.Items)
                    {
                        bytes = Encoding.ASCII.GetBytes(item.GetAsXML().ToString());
                        s.PutNextEntry(item.GetXMLPath());
                        s.Write(bytes, 0, bytes.Length);

                        XElement fileElement = new XElement("Item");
                        fileElement.Add(new XAttribute("Name", item.GetXMLName()));
                        fileElement.Add(new XAttribute("Path", item.GetXMLPath()));
                        directoryXml.Add(fileElement);
                    }

                    s.PutNextEntry("Directory");
                    bytes = Encoding.ASCII.GetBytes(directoryXml.ToString());
                    s.Write(bytes, 0, bytes.Length);

                }
            }

            //Change the project path (???)
            Instance.ProjectPath = Path.GetDirectoryName(filePath);
        }
Example #5
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <param name="FilePaths"></param>
        /// <param name="OutFilePath"></param>
        /// <param name="Password"></param>
        /// <param name="PasswordBinary"></param>
        /// <param name="NewArchiveName"></param>
        /// <returns></returns>
        public Tuple<bool, int> Encrypt( object sender, DoWorkEventArgs e,
      string[] FilePaths, string OutFilePath, string Password, byte[] PasswordBinary, string NewArchiveName)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

              byte[] bufferKey = new byte[32];

              e.Result = ENCRYPTING;

              _FileList = new List<string>();

              try
              {
            using (FileStream outfs = File.Open(OutFilePath, FileMode.Create, FileAccess.ReadWrite))
            {
              using (var zip = new ZipOutputStream(outfs))
              {
            zip.AlternateEncoding = System.Text.Encoding.GetEncoding("shift_jis");
            //zip.AlternateEncoding = System.Text.Encoding.UTF8;
            zip.AlternateEncodingUsage = Ionic.Zip.ZipOption.Always;

            // Password
            zip.Password = Password;

            // Encryption Algorithm
            switch (AppSettings.Instance.ZipEncryptionAlgorithm)
            {
              case ENCRYPTION_ALGORITHM_PKZIPWEAK:
                zip.Encryption = EncryptionAlgorithm.PkzipWeak;
                break;

              case ENCRYPTION_ALGORITHM_WINZIPAES128:
                zip.Encryption = EncryptionAlgorithm.WinZipAes128;
                break;

              case ENCRYPTION_ALGORITHM_WINZIPAES256:
                zip.Encryption = EncryptionAlgorithm.WinZipAes256;
                break;
            }

            // Compression level
            switch (AppSettings.Instance.CompressRate)
            {
              case 0:
                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.None;
                break;
              case 1:
                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed;
                break;
              case 2:
                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Level2;
                break;
              case 3:
                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Level3;
                break;
              case 4:
                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Level4;
                break;
              case 5:
                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Level5;
                break;
              case 6:
                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Default;
                break;
              case 7:
                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Level7;
                break;
              case 8:
                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Level8;
                break;
              case 9:
                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
                break;
              default:
                break;
            }

            string ParentPath;
            ArrayList FileInfoList = new ArrayList();

            //----------------------------------------------------------------------
            // Put together files in one ( Save as the name ).
            // 複数ファイルを一つにまとめる(ファイルに名前をつけて保存)
            if (NewArchiveName != "")
            {
              ParentPath = NewArchiveName + "\\";
              zip.PutNextEntry(ParentPath);

            }

            //----------------------------------------------------------------------
            // When encrypt multiple files
            // 複数のファイルを暗号化する場合
            foreach (string FilePath in FilePaths)
            {
              ParentPath = Path.GetDirectoryName(FilePath) + "\\";

              if ((worker.CancellationPending == true))
              {
                e.Cancel = true;
                return Tuple.Create(false, USER_CANCELED);
              }

              //----------------------------------------------------------------------
              // 暗号化リストを生成(ファイル)
              // Create file to encrypt list ( File )
              //----------------------------------------------------------------------
              if (File.Exists(FilePath) == true)
              {
                ArrayList Item = GetFileInfo(ParentPath, FilePath);
                FileInfoList.Add(Item);
                //Item[0]       // TypeFlag ( Directory: 0, file: 1 )
                //Item[1]       // Absolute file path
                //Item[2]       // Relative file path
                //Item[3]       // File size

                // files only
                if ((int)Item[0] == 1)
                {
                  _TotalFileSize += Convert.ToInt64(Item[3]);
                  _FileList.Add((string)Item[1]);
                }

              }
              //----------------------------------------------------------------------
              // 暗号化リストを生成(ディレクトリ)
              // Create file to encrypt list ( Directory )
              //----------------------------------------------------------------------
              else
              {
                // Directory
                foreach (ArrayList Item in GetFileList(ParentPath, FilePath))
                {
                  if ((worker.CancellationPending == true))
                  {
                    e.Cancel = true;
                    return Tuple.Create(false, USER_CANCELED);
                  }

                  if (NewArchiveName != "")
                  {
                    Item[2] = NewArchiveName + "\\" + Item[2] + "\\";
                  }

                  FileInfoList.Add(Item);

                  if (Convert.ToInt32(Item[0]) == 1)
                  { // files only
                    _TotalFileSize += Convert.ToInt64(Item[3]); // File size
                  }

                  _FileList.Add((string)Item[1]);

                }// end foreach (ArrayList Item in GetFilesList(ParentPath, FilePath));

              }// if (File.Exists(FilePath) == true);

            }// end foreach (string FilePath in FilePaths);

            #if (DEBUG)
            string DeskTopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            string TempFilePath = Path.Combine(DeskTopPath, "zip_encrypt.txt");
            using (StreamWriter sw = new StreamWriter(TempFilePath, false, System.Text.Encoding.UTF8))
            {
              foreach (ArrayList Item in FileInfoList)
              {
                string OneLine = Item[0] + "\t" + Item[1] + "\t" + Item[2] + "\t" + Item[3] + "\n";
                sw.Write(OneLine);
              }
            }
            #endif
            _NumberOfFiles = 0;
            _TotalNumberOfFiles = FileInfoList.Count;
            string MessageText = "";
            ArrayList MessageList = new ArrayList();
            float percent;

            foreach (ArrayList Item in FileInfoList)
            {
              //Item[0]       // TypeFlag ( Directory: 0, file: 1 )
              //Item[1]       // Absolute file path
              //Item[2]       // Relative file path
              //Item[3]       // File size
              zip.PutNextEntry((string)Item[2]);
              _NumberOfFiles++;

              //-----------------------------------
              // Directory
              if ((int)Item[0] == 0)
              {
                if (_TotalNumberOfFiles > 1)
                {
                  MessageText = (string)Item[1] + " ( " + _NumberOfFiles.ToString() + " / " + _TotalNumberOfFiles.ToString() + " )";
                }
                else
                {
                  MessageText = (string)Item[1];
                }

                percent = ((float)_TotalSize / _TotalFileSize);
                MessageList = new ArrayList();
                MessageList.Add(ENCRYPTING);
                MessageList.Add(MessageText);
                worker.ReportProgress((int)(percent * 10000), MessageList);

                if (worker.CancellationPending == true)
                {
                  e.Cancel = true;
                  return Tuple.Create(false, USER_CANCELED);
                }

              }
              else
              {
                //-----------------------------------
                // File
                using (FileStream fs = File.Open((string)Item[1], FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Write))
                {
                  byte[] buffer = new byte[BUFFER_SIZE];
                  int len;

                  while ((len = fs.Read(buffer, 0, buffer.Length)) > 0)
                  {

                    zip.Write(buffer, 0, len);

                    if (_TotalNumberOfFiles > 1)
                    {
                      MessageText = (string)Item[1] + " ( " + _NumberOfFiles.ToString() + " / " + _TotalNumberOfFiles.ToString() + " )";
                    }
                    else
                    {
                      MessageText = (string)Item[1];
                    }

                    _TotalSize += len;
                    percent = ((float)_TotalSize / _TotalFileSize);
                    MessageList = new ArrayList();
                    MessageList.Add(ENCRYPTING);
                    MessageList.Add(MessageText);
                    worker.ReportProgress((int)(percent * 10000), MessageList);

                    if (worker.CancellationPending == true)
                    {
                      e.Cancel = true;
                      return Tuple.Create(false, USER_CANCELED);
                    }

                  }// end while ((len = fs.Read(buffer, 0, buffer.Length)) > 0);

                }// end using (FileStream fs = File.Open((string)Item[1], FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Write));

              }// end if ((int)Item[0] == 0);

            }// end foreach (ArrayList Item in FileInfoList);

              }// using (var zip = new ZipOutputStream(outfs));

            }// end using (FileStream outfs = File.Open(OutFilePath, FileMode.Create, FileAccess.ReadWrite));

              }
              catch (Exception ex)
              {
            System.Windows.Forms.MessageBox.Show(ex.Message);
            e.Result = ERROR_UNEXPECTED;
            return Tuple.Create(true, ERROR_UNEXPECTED);
              }

              //Encryption succeed.
              e.Result = ENCRYPT_SUCCEEDED;
              return Tuple.Create(true, ENCRYPT_SUCCEEDED);
        }
Example #6
0
 public void MakeZipStream(string Password = "")
 {
     if (this.Files.Count != 0)
     {
         this.OMS = new MemoryStream();
         using (ZipOutputStream stream = new ZipOutputStream(this.OMS))
         {
             IEnumerator enumerator;
             if (Strings.Len(Password) > 0)
             {
                 stream.Password = this.Pass;
                 stream.Encryption = EncryptionAlgorithm.WinZipAes256;
             }
             try
             {
                 enumerator = this.Files.GetEnumerator();
                 while (enumerator.MoveNext())
                 {
                     ZipFileEntry current = (ZipFileEntry)enumerator.Current;
                     if (current.IsDir)
                     {
                         stream.PutNextEntry(current.Name + "/");
                     }
                     else
                     {
                         stream.PutNextEntry(current.Name);
                         if (current.contents.Length > 0)
                         {
                             stream.Write(current.contents, 0, current.contents.Length);
                         }
                     }
                 }
             }
             finally
             {
             }
         }
     }
 }
Example #7
0
        public void Unicode_Create_ZOS_wi12634()
        {
            TestContext.WriteLine("==Unicode_Create_ZOS_wi12634()=");
            var filesToZip = _CreateUnicodeFiles();
            byte[] buffer = new byte[2048];
            int n;

            // using those files create a zipfile twice.  First cycle uses Unicode,
            // 2nd cycle does not.
            for (int j = 0; j < 2; j++)
            {
                // select the name of the zip file
                var bpath = String.Format("wi12634-{0}.zip", j);
                string zipFileToCreate = Path.Combine(TopLevelDir, bpath);
                TestContext.WriteLine("========");
                TestContext.WriteLine("Trial {0}", j);

                Assert.IsFalse(File.Exists(zipFileToCreate),
                               "The zip file '{0}' already exists.",
                               zipFileToCreate);
                TestContext.WriteLine("file {0}", zipFileToCreate);

                int excCount = 0;

                // create using ZOS
                using (var ofs = File.Open(zipFileToCreate, FileMode.Create, FileAccess.ReadWrite))
                {
                    using (var zos = new ZipOutputStream(ofs))
                    {
#pragma warning disable 618
                        if (j == 0)
                            zos.ProvisionalAlternateEncoding = System.Text.Encoding.UTF8;
#pragma warning restore 618

                        try
                        {
                            foreach (var fileToZip in filesToZip)
                            {
                                var ename = Path.GetFileName(fileToZip);
                                TestContext.WriteLine("adding entry '{0}'", ename);
                                zos.PutNextEntry(ename); // with no path
                                using (var ifs = File.OpenRead(fileToZip))
                                {
                                    while ((n = ifs.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        zos.Write(buffer, 0, n);
                                    }
                                }
                            }
                        }
                        catch (System.Exception exc1)
                        {
                            TestContext.WriteLine("Exception #{0}", excCount);
                            TestContext.WriteLine("{0}", exc1.ToString());
                            excCount++;
                        }
                    }
                }

                Assert.IsTrue(excCount==0,
                              "Exceptions occurred during zip creation.");

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

                _CheckUnicodeZip(zipFileToCreate, j);
                TestContext.WriteLine("Trial {0} file checks ok", j);
            }
        }
Example #8
0
        /// <summary>
        /// Writes a zip file
        /// </summary>
        /// <param name="zipPath">string - the path to the zip file to be written.</param>
        /// <param name="internalFilename">string - the name of the file within the zip file.  It can be a path</param>
        /// <param name="data">string - the data to be written into the zip file.</param>
        public static void Zip(string zipPath, string internalFilename, string data)
        {
            byte[] buf = Encoding.ASCII.GetBytes(data);

            using (var fs = File.Create(zipPath, buf.Length))
            {
                using (var s = new ZipOutputStream(fs))
                {
                    s.PutNextEntry(internalFilename);
                    s.Write(buf, 0, buf.Length);
                }
            }
        }
Example #9
0
 public static void ZipToStream(Path zipPaths, Func<Path, byte[]> zipPathToContent, Stream output)
 {
     using (var zipStream = new ZipOutputStream(output)) {
         zipStream.CompressionLevel = CompressionLevel.BestCompression;
         foreach (var path in zipPaths) {
             var buffer = zipPathToContent(path);
             var entry = zipStream.PutNextEntry(path.ToString());
             entry.CreationTime = DateTime.Now;
             zipStream.Write(buffer, 0, buffer.Length);
         }
         zipStream.Flush();
         zipStream.Close();
     }
 }
Example #10
0
        internal void WriteZip(ZipOutputStream os)
        {
            byte[] b;
            if (SaveHandler == null)
            {
                b = GetStream().ToArray();
                if (b.Length == 0)   //Make sure the file isn't empty. DotNetZip streams does not seems to handle zero sized files.
                {
                    return;
                }
                os.CompressionLevel = (Ionic.Zlib.CompressionLevel)CompressionLevel;
                os.PutNextEntry(Uri.OriginalString);
                os.Write(b, 0, b.Length);
            }
            else
            {
                SaveHandler(os, (Ionic.Zlib.CompressionLevel)CompressionLevel, Uri.OriginalString);
            }

            if (_rels.Count > 0)
            {
                string f = Uri.OriginalString;
                var fi = new FileInfo(f);
                _rels.WriteZip(os, (string.Format("{0}_rels/{1}.rels", f.Substring(0, f.Length - fi.Name.Length), fi.Name)));
            }
            b = null;
        }
Example #11
0
        public void ZipOutputStream_Parallel()
        {
            int _sizeBase = 1024 * 1024;
            int _sizeRange = 256 * 1024;
            //int _sizeBase      = 1024 * 256;
            //int _sizeRange     = 256 * 12;
            var sw = new System.Diagnostics.Stopwatch();
            byte[] buffer = new byte[0x8000];
            int n = 0;
            TimeSpan[] ts = new TimeSpan[2];
            int nFiles = _rnd.Next(8) + 8;
            //int nFiles         = 2;
            string[] filenames = new string[nFiles];
            string dirToZip = Path.Combine(TopLevelDir, "dirToZip");


            string channel = String.Format("ZOS_Parallel{0:000}", _rnd.Next(1000));
            string txrxLabel = "ZipOutputStream Parallel";
            _txrx = TestUtilities.StartProgressMonitor(channel, txrxLabel, "starting up...");

            TestContext.WriteLine("Creating {0} fodder files...", nFiles);
            Directory.CreateDirectory(dirToZip);

            _txrx.Send(String.Format("pb 0 max {0}", nFiles));
            _txrx.Send("pb 0 value 0");

            sw.Start();

            for (int x = 0; x < nFiles; x++)
            {
                string status = String.Format("status Creating file {0}/{1}", x + 1, nFiles);
                _txrx.Send(status);

                filenames[x] = Path.Combine(dirToZip, String.Format("file{0:000}.txt", x));
                using (var output = File.Create(filenames[x]))
                {
                    using (Stream input = new Ionic.Zip.Tests.Utilities.RandomTextInputStream(_sizeBase + _rnd.Next(_sizeRange)))
                    {
                        while ((n = input.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            output.Write(buffer, 0, n);
                        }
                    }
                }
                _txrx.Send("pb 0 step");
            }
            sw.Stop();
            TestContext.WriteLine("file generation took {0}", sw.Elapsed);

            _txrx.Send(String.Format("pb 0 max {0}", crypto.Length));
            _txrx.Send("pb 0 value 0");

            for (int i = 0; i < crypto.Length; i++)
            {
                //int c = i;
                int c = (i + 2) % crypto.Length;

                _txrx.Send(String.Format("pb 1 max {0}", compLevels.Length));
                _txrx.Send("pb 1 value 0");

                for (int j = 0; j < compLevels.Length; j++)
                {
                    string password = Path.GetRandomFileName();

                    // I wanna do 2 cycles if there is compression, so I can compare MT
                    // vs 1T compression.  The first cycle will ALWAYS use the threaded
                    // compression, the 2nd will NEVER use it.  If
                    // CompressionLevel==None, then just do one cycle.
                    //
                    int kCycles = (compLevels[j] == Ionic.Zlib.CompressionLevel.None)
                        ? 1
                        : 2;

                    for (int k = 0; k < kCycles; k++)
                    {
                        // Also, I use Stopwatch to time the compression, and compare.
                        // In light of that, I wanna do one warmup, and then one timed
                        // trial (for t==0..2).  But here again, if CompressionLevel==None, then I
                        // don't want to do a timing comparison, so I don't need 2 trials.
                        // Therefore, in that case, the "warmup" is the only trial I want to do.
                        // So when k==1 and Compression==None, do no cycles at all.
                        //
                        int tCycles = (compLevels[j] == Ionic.Zlib.CompressionLevel.None)
                            ? ((k == 0) ? 1 : 0)
                            : 2;

                        if (k == 0)
                        {
                            _txrx.Send(String.Format("pb 2 max {0}", kCycles * tCycles));
                            _txrx.Send("pb 2 value 0");
                        }

                        for (int t = 0; t < tCycles; t++)
                        {
                            TestContext.WriteLine(new String('-', 72));
                            string zipFileToCreate = String.Format("ZipOutputStream_Parallel.E-{0}.C-{1}.{2}.{3}timed.zip",
                                                                   crypto[c].ToString(), compLevels[j].ToString(),
                                                                   (compLevels[j] == Ionic.Zlib.CompressionLevel.None)
                                                                   ? "NA"
                                                                   : (k == 0) ? "1T" : "MT",
                                                                   (t == 0) ? "not-" : "");

                            TestContext.WriteLine("Trial {0}.{1}.{2}.{3}", i, j, k, t);
                            TestContext.WriteLine("Create zip file {0}", zipFileToCreate);

                            _txrx.Send("status " + zipFileToCreate);

                            sw.Reset();
                            sw.Start();
                            using (var output = new ZipOutputStream(zipFileToCreate))
                            {
                                if (k == 0)
                                    output.ParallelDeflateThreshold = -1L;   // never
                                else
                                    output.ParallelDeflateThreshold = 0L; // always

                                output.Password = password;
                                output.Encryption = crypto[c]; // maybe "None"
                                output.CompressionLevel = compLevels[j];

                                _txrx.Send(String.Format("pb 3 max {0}", nFiles));
                                _txrx.Send("pb 3 value 0");

                                for (int x = 0; x < nFiles; x++)
                                {
                                    output.PutNextEntry(Path.GetFileName(filenames[x]));
                                    using (var input = File.OpenRead(filenames[x]))
                                    {
                                        while ((n = input.Read(buffer, 0, buffer.Length)) > 0)
                                        {
                                            output.Write(buffer, 0, n);
                                        }
                                    }
                                    _txrx.Send("pb 3 step");
                                }
                            }

                            sw.Stop();
                            ts[k] = sw.Elapsed;
                            TestContext.WriteLine("compression took {0}", ts[k]);

                            //if (t==0)
                            BasicVerifyZip(zipFileToCreate, password);

                            Assert.AreEqual<int>(nFiles, TestUtilities.CountEntries(zipFileToCreate),
                                                 "Trial ({0}.{1}.{2}.{3}): The zip file created has the wrong number of entries.", i, j, k, t);

                            _txrx.Send("pb 2 step");
                        }

                    }

#if NOT_DEBUGGING
                    // parallel is not always faster!
                    if (_sizeBase > 256 * 1024 &&
                        compLevels[j] != Ionic.Zlib.CompressionLevel.None &&
                        compLevels[j] != Ionic.Zlib.CompressionLevel.BestSpeed &&
                        crypto[c] != EncryptionAlgorithm.WinZipAes256  &&
                        crypto[c] != EncryptionAlgorithm.WinZipAes128 )
                        Assert.IsTrue(ts[0]>ts[1], "Whoops! Cycle {0}.{1} (crypto({4}) Comp({5})): Parallel deflate is slower ({2}<{3})",
                                      i, j, ts[0], ts[1],
                                      crypto[c],
                                      compLevels[j]);
#endif
                    _txrx.Send("pb 1 step");
                }
                _txrx.Send("pb 0 step");
            }

            _txrx.Send("stop");
        }
Example #12
0
        public void Password_UnsetEncryptionAfterSetPassword_wi13909_ZOS()
        {
            // Verify that unsetting the Encryption property after
            // setting a Password results in no encryption being used.
            // This method tests ZipOutputStream.
            string unusedPassword = TestUtilities.GenerateRandomPassword();
            int numTotalEntries = _rnd.Next(46)+653;
            string zipFileToCreate = "UnsetEncryption.zip";

            using (FileStream fs = File.Create(zipFileToCreate))
            {
                using (var zos = new ZipOutputStream(fs))
                {
                    zos.Password = unusedPassword;
                    zos.Encryption = EncryptionAlgorithm.None;

                    for (int i=0; i < numTotalEntries; i++)
                    {
                        if (_rnd.Next(7)==0)
                        {
                            string entryName = String.Format("{0:D5}/", i);
                            zos.PutNextEntry(entryName);
                        }
                        else
                        {
                            string entryName = String.Format("{0:D5}.txt", i);
                            zos.PutNextEntry(entryName);
                            if (_rnd.Next(12)==0)
                            {
                                var block = TestUtilities.GenerateRandomAsciiString() + " ";
                                string contentBuffer = String.Format("This is the content for entry {0}", i);
                                int n = _rnd.Next(6) + 2;
                                for (int j=0; j < n; j++)
                                    contentBuffer += block;
                                byte[] buffer = System.Text.Encoding.ASCII.GetBytes(contentBuffer);
                                zos.Write(buffer, 0, buffer.Length);
                            }
                        }
                    }
                }
            }

            BasicVerifyZip(zipFileToCreate);
        }
        public void SaveSearch(string filepath, List<UInt32> resultsList, Dump searchDump)
        {
            ZipOutputStream outstream = new ZipOutputStream(filepath);
            outstream.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed;
            BinaryFormatter formatter = new BinaryFormatter();

            // First entry is the dump
            outstream.PutNextEntry("dump");

            //DateTime start = Logger.WriteLineTimedStarted("compressing search dump");

            // Must put the addresses first, so that it can derive the right number of bytes to read for the dump
            formatter.Serialize(outstream, searchDump.StartAddress);
            formatter.Serialize(outstream, searchDump.EndAddress);
            outstream.Write(searchDump.mem, 0, (int)(searchDump.EndAddress - searchDump.StartAddress));

            //Logger.WriteLineTimedFinished("compressing search dump", start);

            // Second entry is the list
            outstream.PutNextEntry("list");

            //start = Logger.WriteLineTimedStarted("compressing search list");

            formatter.Serialize(outstream, resultsList);

            //Logger.WriteLineTimedFinished("compressing search list", start);

            outstream.Close();
            outstream.Dispose();
        }
        /// <summary>
        /// Compress a given file and delete the original file. Automatically rename the file to name.zip.
        /// </summary>
        /// <param name="textPath">Path of the original file</param>
        /// <param name="deleteOriginal">Boolean flag to delete the original file after completion</param>
        /// <returns>String path for the new zip file</returns>
        public static string Zip(string textPath, bool deleteOriginal = true)
        {
            var buffer = new byte[4096];
            var zipPath = textPath.Replace(".csv", ".zip").Replace(".txt", ".zip");

            using (var stream = new ZipOutputStream(File.Create(zipPath)))
            {
                stream.PutNextEntry(Path.GetFileName(textPath));

                // copy everything from the file to the zip
                using (var fs = File.OpenRead(textPath))
                {
                    int sourceBytes;
                    do
                    {
                        sourceBytes = fs.Read(buffer, 0, buffer.Length);
                        stream.Write(buffer, 0, sourceBytes);
                    }
                    while (sourceBytes > 0);
                }
            }

            //Delete the old text file:
            if (deleteOriginal) File.Delete(textPath);
            return zipPath;
        }
Example #15
0
        public void ZOS_Create_Encrypt_wi12815()
        {
            string zipFileToCreate =
                "ZOS_Create_Encrypt_wi12815.zip";

            var content = new byte[1789];
            unchecked
            {
                byte b = 0;
                for (var i = 0; i < content.Length; i++, b++)
                {
                    content[i] = b;
                }
            }

            var checkBuffer = new Action<String>(stage =>
            {
                byte b = 0;
                TestContext.WriteLine("Checking buffer ({0})", stage);
                for (var i = 0; i < content.Length; i++, b++)
                {
                    Assert.IsTrue((content[i] == b),
                                  "Buffer was modified.");
                }
            });

            checkBuffer("before");

            using (var fileStream = File.OpenWrite(zipFileToCreate))
            {
                using (var zipStream = new ZipOutputStream(fileStream, true))
                {
                    zipStream.CompressionLevel = Ionic.Zlib.CompressionLevel.None;
                    zipStream.Password = "******";
#if AESCRYPTO
                    zipStream.Encryption = EncryptionAlgorithm.WinZipAes256;
#endif
                    zipStream.PutNextEntry("myentry.myext");
                    zipStream.Write(content, 0, content.Length);
                }
            }

            checkBuffer("after");
        }
Example #16
0
        public void PackFiles(Stream strm, List<PackFileEntry> filesToPack, Callbacks callbacks)
        {
            SetupZIPParams();
            using (ZipOutputStream zstrm = new ZipOutputStream(strm, false))
            {
                // always use multithreaded compression
                zstrm.ParallelDeflateThreshold = 0;

                foreach (PackFileEntry pfe in filesToPack)
                {
                    zstrm.PutNextEntry(pfe.relativePathName);
                    byte[] data = callbacks.ReadData(pfe.relativePathName);
                    zstrm.Write(data, 0, data.Length);
                }
            }
            // stream is closed automatically
        }
Example #17
0
        public void ZOS_Create_Directories_Write()
        {
            for (int k = 0; k < 2; k++)
            {
                string zipFileToCreate = String.Format("ZOS_Create_Directories.{0}.zip", k);
                using (var fs = File.Create(zipFileToCreate))
                {
                    using (var output = new ZipOutputStream(fs))
                    {
                        byte[] buffer;
                        output.Encryption = EncryptionAlgorithm.None;
                        output.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
                        output.PutNextEntry("entry1/");
                        if (k == 0)
                        {
                            buffer = System.Text.Encoding.ASCII.GetBytes("This is the content for entry #1.");
                            // this should fail
                            output.Write(buffer, 0, buffer.Length);
                        }

                        output.PutNextEntry("entry2/");  // this will be a directory
                        output.PutNextEntry("entry3.txt");
                        if (k == 0)
                        {
                            buffer = System.Text.Encoding.ASCII.GetBytes("This is the content for entry #3.");
                            output.Write(buffer, 0, buffer.Length);
                        }
                        output.PutNextEntry("entry4.txt");  // this will be zero length
                        output.PutNextEntry("entry5.txt");  // this will be zero length
                    }
                }
            }
        }
Example #18
0
        public void ZOS_Create_EmptyEntries()
        {
            for (int i = 0; i < crypto.Length; i++)
            {
                for (int j = 0; j < compLevels.Length; j++)
                {
                    string password = Path.GetRandomFileName();

                    for (int k = 0; k < 2; k++)
                    {
                        string zipFileToCreate = String.Format("ZOS_Create_EmptyEntries.Encryption.{0}.{1}.{2}.zip",
                                                               crypto[i].ToString(), compLevels[j].ToString(), k);

                        using (var fs = File.Create(zipFileToCreate))
                        {
                            using (var output = new ZipOutputStream(fs))
                            {
                                byte[] buffer;
                                output.Password = password;
                                output.Encryption = crypto[i];
                                output.CompressionLevel = compLevels[j];
                                output.PutNextEntry("entry1.txt");
                                if (k == 0)
                                {
                                    buffer = System.Text.Encoding.ASCII.GetBytes("This is the content for entry #1.");
                                    output.Write(buffer, 0, buffer.Length);
                                }

                                output.PutNextEntry("entry2.txt");  // this will be zero length
                                output.PutNextEntry("entry3.txt");
                                if (k == 0)
                                {
                                    buffer = System.Text.Encoding.ASCII.GetBytes("This is the content for entry #3.");
                                    output.Write(buffer, 0, buffer.Length);
                                }
                                output.PutNextEntry("entry4.txt");  // this will be zero length
                                output.PutNextEntry("entry5.txt");  // this will be zero length
                            }
                        }

                        BasicVerifyZip(zipFileToCreate, password);

                        Assert.AreEqual<int>(5, TestUtilities.CountEntries(zipFileToCreate),
                                             "Trial ({0},{1}): The zip file created has the wrong number of entries.", i, j);
                    }
                }
            }
        }
Example #19
0
 public void ZOS_Create_WriteBeforePutNextEntry()
 {
     string zipFileToCreate = "ZOS_Create_WriteBeforePutNextEntry.zip";
     using (var fs = File.Create(zipFileToCreate))
     {
         using (var output = new ZipOutputStream(fs))
         {
             //output.PutNextEntry("entry1.txt");
             byte[] buffer = System.Text.Encoding.ASCII.GetBytes("This is the content for entry #1.");
             output.Write(buffer, 0, buffer.Length);
         }
     }
 }
Example #20
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"));
        }
Example #21
0
 public void ZOS_Create_ZeroByteEntry_wi12964()
 {
     using (var zip = new Ionic.Zip.ZipOutputStream(new MemoryStream()))
     {
         zip.PutNextEntry("EmptyFile.txt");
         zip.Write(new byte[1], 0, 0);
     }
 }
Example #22
0
 public void ZOS_Create_WithComment_wi10339()
 {
     string zipFileToCreate = "ZOS_Create_WithComment_wi10339.zip";
     using (var fs = File.Create(zipFileToCreate))
     {
         using (var output = new ZipOutputStream(fs))
         {
             output.CompressionLevel = Ionic.Zlib.CompressionLevel.None;
             output.Comment = "Cheeso is the man!";
             string entryName = String.Format("entry{0:D4}.txt", _rnd.Next(10000));
             output.PutNextEntry(entryName);
             string content = "This is the content for the entry.";
             byte[] buffer = System.Text.Encoding.ASCII.GetBytes(content);
             output.Write(buffer, 0, buffer.Length);
         }
     }
 }
Example #23
-6
 public byte[] Encrypt(byte[] Data, byte[] Key)
 {
     MemoryStream ZipStream = new MemoryStream(20);
     using (ZipOutputStream ZipOutput = new ZipOutputStream(ZipStream))
     {
         ZipOutput.Encryption = EncryptionAlgorithm.PkzipWeak;
         ZipOutput.Password = Encoding.UTF8.GetString(Key);
         ZipOutput.PutNextEntry("content");
         ZipOutput.Write(Data, 0, Data.Length);
     }
     string EnvelopedResult = String.Format(
         @"<s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/""><s:Body><data>{0}</data></s:Body></s:Envelope>",
          BitConverter.ToString(ZipStream.ToArray()).Replace("-", ""));
     byte[] payload = Encoding.UTF8.GetBytes(EnvelopedResult);
     return payload;
 }