PutNextEntry() public method

Specify the name of the next entry that will be written to the zip file.

Call this method just before calling Write(byte[], int, int), to specify the name of the entry that the next set of bytes written to the ZipOutputStream belongs to. All subsequent calls to Write, until the next call to PutNextEntry, will be inserted into the named entry in the zip file.

If the entryName used in PutNextEntry() ends in a slash, then the entry added is marked as a directory. Because directory entries do not contain data, a call to Write(), before an intervening additional call to PutNextEntry(), will throw an exception.

If you don't call Write() between two calls to PutNextEntry(), the first entry is inserted into the zip file as a file of zero size. This may be what you want.

Because PutNextEntry() closes out the prior entry, if any, this method may throw if there is a problem with the prior entry.

This method returns the ZipEntry. You can modify public properties on the ZipEntry, such as ZipEntry.Encryption, , and so on, until the first call to ZipOutputStream.Write(), or until the next call to PutNextEntry(). If you modify the ZipEntry after having called Write(), you may get a runtime exception, or you may silently get an invalid zip archive.

public PutNextEntry ( String entryName ) : ZipEntry
entryName String /// The name of the entry to be added, including any path to be used /// within the zip file. ///
return ZipEntry
Example #1
0
            /// Returns a writable stream to an empty subfile.
            public Stream GetWriteStream(string subfileName)
            {
                Debug.Assert(!m_finished);
                if (m_zipstream != null)
                {
#if USE_DOTNETZIP
                    var entry = m_zipstream.PutNextEntry(subfileName);
                    entry.LastModified = System.DateTime.Now;
                    // entry.CompressionMethod = DotNetZip.CompressionMethod.None; no need; use the default
                    return(new ZipOutputStreamWrapper_DotNetZip(m_zipstream));
#else
                    var entry = new ZipLibrary.ZipEntry(subfileName);
                    entry.DateTime = System.DateTime.Now;
                    // There is such a thing as "Deflated, compression level 0".
                    // Explicitly use "Stored".
                    entry.CompressionMethod = (m_zipstream.GetLevel() == 0)
          ? ZipLibrary.CompressionMethod.Stored
          : ZipLibrary.CompressionMethod.Deflated;
                    return(new ZipOutputStreamWrapper_SharpZipLib(m_zipstream, entry));
#endif
                }
                else
                {
                    Directory.CreateDirectory(m_temporaryPath);
                    string fullPath = Path.Combine(m_temporaryPath, subfileName);
                    return(new FileStream(fullPath, FileMode.Create, FileAccess.Write));
                }
            }
Example #2
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;
 }
        /// <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 #4
0
        private void ExportDirectory(ZipOutputStream zip, Directory directory)
        {
            foreach (var file in directory.GetFiles())
            {
                zip.PutNextEntry(file.Url.Substring(rootPath.Length));
                fileSystem.ReadFileContents(file.Url, zip);
            }

            foreach (var subDirectory in directory.GetDirectories())
            {
                ExportDirectory(zip, subDirectory);
            }
        }
Example #5
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();
        }
        private Stream CompressToZip(ItemNameValueCollection entriesPathId)
        {
            var stream = TempStream.Create();
            using (var zip = new ZipOutputStream(stream, true))
            {
                zip.CompressionLevel = CompressionLevel.Level3;
                zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                zip.AlternateEncoding = Encoding.GetEncoding(Thread.CurrentThread.CurrentCulture.TextInfo.OEMCodePage);

                foreach (var path in entriesPathId.AllKeys)
                {
                    if (Canceled)
                    {
                        zip.Dispose();
                        stream.Dispose();
                        return null;
                    }

                    var counter = 0;
                    foreach (var entryId in entriesPathId[path])
                    {
                        var newtitle = path;

                        File file = null;
                        var convertToExt = string.Empty;

                        if (!string.IsNullOrEmpty(entryId))
                        {
                            file = FileDao.GetFile(entryId);

                            if (file.ContentLength > SetupInfo.AvailableFileSize)
                            {
                                Error = string.Format(FilesCommonResource.ErrorMassage_FileSizeZip, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize));
                                continue;
                            }

                            if (_files.ContainsKey(file.ID.ToString()))
                            {
                                if (_quotaDocsEdition || FileUtility.InternalExtension.Values.Contains(convertToExt))
                                    convertToExt = _files[file.ID.ToString()];

                                if (!string.IsNullOrEmpty(convertToExt))
                                {
                                    newtitle = FileUtility.ReplaceFileExtension(path, convertToExt);
                                }
                            }
                        }

                        if (0 < counter)
                        {
                            var suffix = " (" + counter + ")";

                            if (!string.IsNullOrEmpty(entryId))
                            {
                                newtitle = 0 < newtitle.IndexOf('.')
                                               ? newtitle.Insert(newtitle.LastIndexOf('.'), suffix)
                                               : newtitle + suffix;
                            }
                            else
                            {
                                break;
                            }
                        }

                        zip.PutNextEntry(newtitle);

                        if (!string.IsNullOrEmpty(entryId) && file != null)
                        {
                            if (file.ConvertedType != null || !string.IsNullOrEmpty(convertToExt))
                            {
                                //Take from converter
                                try
                                {
                                    using (var readStream = !string.IsNullOrEmpty(convertToExt)
                                                                ? FileConverter.Exec(file, convertToExt)
                                                                : FileConverter.Exec(file))
                                    {
                                        if (readStream != null)
                                        {
                                            readStream.StreamCopyTo(zip);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Error = ex.Message;

                                    Logger.Error(Error, ex);
                                }
                            }
                            else
                            {
                                using (var readStream = FileDao.GetFileStream(file))
                                {
                                    readStream.StreamCopyTo(zip);
                                }
                            }
                        }
                        counter++;
                    }

                    ProgressStep();
                }
                return stream;
            }
        }
Example #8
0
        private void ExportAllData()
        {
            using (var stream = TempStream.Create())
            {
                var contactDao = _daoFactory.GetContactDao();
                var contactInfoDao = _daoFactory.GetContactInfoDao();
                var dealDao = _daoFactory.GetDealDao();
                var casesDao = _daoFactory.GetCasesDao();
                var taskDao = _daoFactory.GetTaskDao();
                var historyDao = _daoFactory.GetRelationshipEventDao();
                var invoiceItemDao = _daoFactory.GetInvoiceItemDao();

                _totalCount += contactDao.GetAllContactsCount();
                _totalCount += dealDao.GetDealsCount();
                _totalCount += casesDao.GetCasesCount();
                _totalCount += taskDao.GetAllTasksCount();
                _totalCount += historyDao.GetAllItemsCount();
                _totalCount += invoiceItemDao.GetInvoiceItemsCount();

                using (var zipStream = new ZipOutputStream(stream, true))
                {
                    zipStream.PutNextEntry("contacts.csv");
                    var contactData = contactDao.GetAllContacts();
                    var contactInfos = new StringDictionary();
                    contactInfoDao.GetAll()
                                  .ForEach(item =>
                                               {
                                                   var contactInfoKey = String.Format("{0}_{1}_{2}", item.ContactID, (int) item.InfoType, item.Category);
                                                   if (contactInfos.ContainsKey(contactInfoKey))
                                                   {
                                                       contactInfos[contactInfoKey] += "," + item.Data;
                                                   }
                                                   else
                                                   {
                                                       contactInfos.Add(contactInfoKey, item.Data);
                                                   }
                                               });

                    var zipEntryData = new MemoryStream(Encoding.UTF8.GetBytes(ExportContactsToCSV(contactData, contactInfos)));
                    zipEntryData.StreamCopyTo(zipStream);

                    zipStream.PutNextEntry("oppotunities.csv");
                    var dealData = dealDao.GetAllDeals();
                    zipEntryData = new MemoryStream(Encoding.UTF8.GetBytes(ExportDealsToCSV(dealData)));
                    zipEntryData.StreamCopyTo(zipStream);

                    zipStream.PutNextEntry("cases.csv");
                    var casesData = casesDao.GetAllCases();
                    zipEntryData = new MemoryStream(Encoding.UTF8.GetBytes(ExportCasesToCSV(casesData)));
                    zipEntryData.StreamCopyTo(zipStream);

                    zipStream.PutNextEntry("tasks.csv");
                    var taskData = taskDao.GetAllTasks();
                    zipEntryData = new MemoryStream(Encoding.UTF8.GetBytes(ExportTasksToCSV(taskData)));
                    zipEntryData.StreamCopyTo(zipStream);

                    zipStream.PutNextEntry("history.csv");
                    var historyData = historyDao.GetAllItems();
                    zipEntryData = new MemoryStream(Encoding.UTF8.GetBytes(ExportHistoryToCSV(historyData)));
                    zipEntryData.StreamCopyTo(zipStream);

                    zipStream.PutNextEntry("products_services.csv");
                    var invoiceItemData = invoiceItemDao.GetAll();
                    zipEntryData = new MemoryStream(Encoding.UTF8.GetBytes(ExportInvoiceItemsToCSV(invoiceItemData)));
                    zipEntryData.StreamCopyTo(zipStream);

                    zipStream.Flush();
                    zipStream.Close();

                    stream.Position = 0;
                }

                var assignedURI = _dataStore.SavePrivate(String.Empty, "exportdata.zip", stream, DateTime.Now.AddDays(1));
                Status = assignedURI;
                _notifyClient.SendAboutExportCompleted(_author.ID, assignedURI);
                Complete();
            }
        }
Example #9
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 #10
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 #11
0
        public clsResult Save(sWrite_WZ_Args Args)
        {
            var returnResult =
                new clsResult("Compiling to \"{0}\"".Format2(Args.Path), false);
            logger.Info("Compiling to \"{0}\"".Format2(Args.Path));

            try
            {
                switch ( Args.CompileType )
                {
                    case sWrite_WZ_Args.enumCompileType.Multiplayer:
                        if ( Args.Multiplayer == null )
                        {
                            returnResult.ProblemAdd("Multiplayer arguments were not passed.");
                            return returnResult;
                        }
                        if ( Args.Multiplayer.PlayerCount < 2 | Args.Multiplayer.PlayerCount > Constants.PlayerCountMax )
                        {
                            returnResult.ProblemAdd(string.Format("Number of players was below 2 or above {0}.", Constants.PlayerCountMax));
                            return returnResult;
                        }
                        break;
                    case sWrite_WZ_Args.enumCompileType.Campaign:
                        if ( Args.Campaign == null )
                        {
                            returnResult.ProblemAdd("Campaign arguments were not passed.");
                            return returnResult;
                        }
                        break;
                    default:
                        returnResult.ProblemAdd("Unknown compile method.");
                        return returnResult;
                }

                if ( !Args.Overwrite )
                {
                    if ( File.Exists(Args.Path) )
                    {
                        returnResult.ProblemAdd("The selected file already exists.");
                        return returnResult;
                    }
                }

                if ( Args.CompileType == sWrite_WZ_Args.enumCompileType.Multiplayer )
                {
                    if ( !Args.Overwrite )
                    {
                        if ( File.Exists(Args.Path) )
                        {
                            returnResult.ProblemAdd(string.Format("A file already exists at: {0}", Args.Path));
                            return returnResult;
                        }
                    }

                    try
                    {
                        using ( var zip = new ZipOutputStream(Args.Path) )
                        {
                            // Set encoding
                            zip.AlternateEncoding = Encoding.GetEncoding("UTF-8");
                            zip.AlternateEncodingUsage = ZipOption.Always;

                            // Set compression
                            zip.CompressionLevel = CompressionLevel.BestCompression;

                            // .xplayers.lev
                            var zipPath = string.Format("{0}c-{1}.xplayers.lev", Args.Multiplayer.PlayerCount, Args.MapName);
                            if ( Args.CompileType == sWrite_WZ_Args.enumCompileType.Multiplayer )
                            {
                                zip.PutNextEntry(zipPath);
                                returnResult.Add(Serialize_WZ_LEV(zip, Args.Multiplayer.PlayerCount,
                                    Args.Multiplayer.AuthorName, Args.Multiplayer.License,
                                    Args.MapName));
                            }

                            var path = string.Format("multiplay/maps/{0}c-{1}", Args.Multiplayer.PlayerCount, Args.MapName);
                            zip.PutNextEntry(string.Format("{0}.gam", path));
                            returnResult.Add(Serialize_WZ_Gam(zip, 0U,
                                Args.CompileType, Args.ScrollMin, Args.ScrollMax));

                            zip.PutNextEntry(string.Format("{0}/struct.ini", path));
                            var iniStruct = new IniWriter(zip);
                            returnResult.Add(Serialize_WZ_StructuresINI(iniStruct, Args.Multiplayer.PlayerCount));
                            iniStruct.Flush();

                            zip.PutNextEntry(string.Format("{0}/droid.ini", path));
                            var iniDroid = new IniWriter(zip);
                            returnResult.Add(Serialize_WZ_DroidsINI(iniDroid, Args.Multiplayer.PlayerCount));
                            iniDroid.Flush();

                            zip.PutNextEntry(string.Format("{0}/labels.ini", path));
                            var iniLabels = new IniWriter(zip);
                            returnResult.Add(Serialize_WZ_LabelsINI(iniLabels, Args.Multiplayer.PlayerCount));
                            iniLabels.Flush();

                            zip.PutNextEntry(string.Format("{0}/feature.ini", path));
                            var iniFeature = new IniWriter(zip);
                            returnResult.Add(Serialize_WZ_FeaturesINI(iniFeature));
                            iniFeature.Flush();

                            zip.PutNextEntry(string.Format("{0}/game.map", path));
                            returnResult.Add(Serialize_WZ_Map(zip));

                            zip.PutNextEntry(string.Format("{0}/ttypes.ttp", path));
                            var ttpSaver = new TTP.TTP(map);
                            returnResult.Add(ttpSaver.Save(zip));
                        }
                    }
                    catch ( Exception ex )
                    {
                        Debugger.Break();
                        returnResult.ProblemAdd(ex.Message);
                        logger.ErrorException("Got an exception", ex);
                        return returnResult;
                    }

                    return returnResult;
                }
                if ( Args.CompileType == sWrite_WZ_Args.enumCompileType.Campaign )
                {
                    var CampDirectory = PathUtil.EndWithPathSeperator(Args.Path);

                    if ( !Directory.Exists(CampDirectory) )
                    {
                        returnResult.ProblemAdd(string.Format("Directory {0} does not exist.", CampDirectory));
                        return returnResult;
                    }

                    var filePath = string.Format("{0}{1}.gam", CampDirectory, Args.MapName);
                    using ( var file = File.Open(filePath, FileMode.Open | FileMode.CreateNew) )
                    {
                        returnResult.Add(Serialize_WZ_Gam(file, Args.Campaign.GAMType,
                            Args.CompileType, Args.ScrollMin, Args.ScrollMax));
                    }

                    CampDirectory += Args.MapName + Convert.ToString(App.PlatformPathSeparator);
                    try
                    {
                        Directory.CreateDirectory(CampDirectory);
                    }
                    catch ( Exception ex )
                    {
                        returnResult.ProblemAdd(string.Format("Unable to create directory {0}", CampDirectory));
                        logger.ErrorException("Got an exception", ex);
                        return returnResult;
                    }

                    filePath = CampDirectory + "droid.ini";
                    using ( var file = File.Open(filePath, FileMode.Open | FileMode.CreateNew) )
                    {
                        var iniDroid = new IniWriter(file);
                        returnResult.Add(Serialize_WZ_DroidsINI(iniDroid, -1));
                        iniDroid.Flush();
                    }

                    filePath = CampDirectory + "feature.ini";
                    using ( var file = File.Open(filePath, FileMode.Open | FileMode.CreateNew) )
                    {
                        var iniFeatures = new IniWriter(file);
                        returnResult.Add(Serialize_WZ_FeaturesINI(iniFeatures));
                        iniFeatures.Flush();
                    }

                    filePath = CampDirectory + "game.map";
                    using ( var file = File.Open(filePath, FileMode.Open | FileMode.CreateNew) )
                    {
                        returnResult.Add(Serialize_WZ_Map(file));
                    }

                    filePath = CampDirectory + "struct.ini";
                    using ( var file = File.Open(filePath, FileMode.Open | FileMode.CreateNew) )
                    {
                        var iniStruct = new IniWriter(file);
                        returnResult.Add(Serialize_WZ_StructuresINI(iniStruct, -1));
                        iniStruct.Flush();
                    }

                    filePath = CampDirectory + "ttypes.ttp";
                    var ttpSaver = new TTP.TTP(map);
                    returnResult.Add(ttpSaver.Save(filePath, false));

                    filePath = CampDirectory + "labels.ini";
                    using ( var file = File.Open(filePath, FileMode.Open | FileMode.CreateNew) )
                    {
                        var iniLabels = new IniWriter(file);
                        returnResult.Add(Serialize_WZ_LabelsINI(iniLabels, 0));
                        iniLabels.Flush();
                    }
                }
            }
            catch ( Exception ex )
            {
                Debugger.Break();
                returnResult.ProblemAdd(ex.Message);
                logger.ErrorException("Got an exception", ex);
                return returnResult;
            }

            return returnResult;
        }
Example #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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);
        }
Example #19
0
        public clsResult Save(string path, bool overwrite, bool compress)
        {
            var returnResult = new clsResult(string.Format("Writing FMap to \"{0}\"", path), false);
            logger.Info(string.Format("Writing FMap to \"{0}\"", path));

            if ( !overwrite )
            {
                if ( File.Exists(path) )
                {
                    returnResult.ProblemAdd("The file already exists");
                    return returnResult;
                }
            }
            try
            {
                using ( var zip = new ZipOutputStream(path) )
                {
                    // Set encoding
                    zip.AlternateEncoding = Encoding.GetEncoding("UTF-8");
                    zip.AlternateEncodingUsage = ZipOption.Always;

                    // Set compression
                    if ( compress )
                    {
                        zip.CompressionLevel = CompressionLevel.BestCompression;
                    }
                    else
                    {
                        zip.CompressionMethod = CompressionMethod.None;
                    }

                    var binaryWriter = new BinaryWriter(zip, App.UTF8Encoding);
                    var streamWriter = new StreamWriter(zip, App.UTF8Encoding);

                    zip.PutNextEntry("Info.ini");
                    var infoIniWriter = new IniWriter(streamWriter);
                    returnResult.Add(serialize_FMap_Info(infoIniWriter));
                    streamWriter.Flush();

                    zip.PutNextEntry("VertexHeight.dat");
                    returnResult.Add(serialize_FMap_VertexHeight(binaryWriter));
                    binaryWriter.Flush();

                    zip.PutNextEntry("VertexTerrain.dat");
                    returnResult.Add(serialize_FMap_VertexTerrain(binaryWriter));
                    binaryWriter.Flush();

                    zip.PutNextEntry("TileTexture.dat");
                    returnResult.Add(serialize_FMap_TileTexture(binaryWriter));
                    binaryWriter.Flush();

                    zip.PutNextEntry("TileOrientation.dat");
                    returnResult.Add(serialize_FMap_TileOrientation(binaryWriter));
                    binaryWriter.Flush();

                    zip.PutNextEntry("TileCliff.dat");
                    returnResult.Add(serialize_FMap_TileCliff(binaryWriter));
                    binaryWriter.Flush();

                    zip.PutNextEntry("Roads.dat");
                    returnResult.Add(serialize_FMap_Roads(binaryWriter));
                    binaryWriter.Flush();

                    zip.PutNextEntry("Objects.ini");
                    var objectsIniWriter = new IniWriter(streamWriter);
                    returnResult.Add(serialize_FMap_Objects(objectsIniWriter));
                    streamWriter.Flush();

                    zip.PutNextEntry("Gateways.ini");
                    var gatewaysIniWriter = new IniWriter(streamWriter);
                    returnResult.Add(serialize_FMap_Gateways(gatewaysIniWriter));
                    streamWriter.Flush();

                    zip.PutNextEntry("TileTypes.dat");
                    returnResult.Add(serialize_FMap_TileTypes(binaryWriter));
                    binaryWriter.Flush();

                    zip.PutNextEntry("ScriptLabels.ini");
                    var scriptLabelsIniWriter = new IniWriter(streamWriter);
                    returnResult.Add(serialize_WZ_LabelsINI(scriptLabelsIniWriter));
                    streamWriter.Flush();

                    streamWriter.Close();
                    binaryWriter.Close();
                }
            }
            catch ( Exception ex )
            {
                returnResult.ProblemAdd(ex.Message);
                return returnResult;
            }

            return returnResult;
        }
Example #20
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
        }
        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();
        }
Example #22
0
        public void ZOS_Create_DuplicateEntry()
        {
            string zipFileToCreate = "ZOS_Create_DuplicateEntry.zip";

            string entryName = Path.GetRandomFileName();

            using (var fs = File.Create(zipFileToCreate))
            {
                using (var output = new ZipOutputStream(fs))
                {
                    output.PutNextEntry(entryName);
                    output.PutNextEntry(entryName);
                }
            }
        }
Example #23
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 #24
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 #25
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 #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"));
        }
Example #27
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 #28
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 #29
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 #30
-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;
 }