Beispiel #1
0
        public void ReplaceMobileProvision(byte[] mobileProvisionBytes)
        {
            m_zipFile.BeginUpdate();
            MemoryStreamDataSource mobileProvisionDataSource = new MemoryStreamDataSource(mobileProvisionBytes);

            m_zipFile.Add(mobileProvisionDataSource, m_appDirectoryPath + MobileProvisionFileName);

            CodeResourcesFile codeResources = GetCodeResourcesFile();

            codeResources.UpdateFileHash(MobileProvisionFileName, mobileProvisionBytes);

            MobileProvisionFile mobileProvision = new MobileProvisionFile(mobileProvisionBytes);
            string provisionedBundleIdentifier  = mobileProvision.PList.Entitlements.BundleIdentifier;

            if (provisionedBundleIdentifier != GetBundleIdentifier())
            {
                // We must update the info.plist's CFBundleIdentifier to match the one from the mobile provision
                InfoFile infoFile = GetInfoFile();
                infoFile.BundleIdentifier = provisionedBundleIdentifier;
                byte[] infoBytes = infoFile.GetBytes();
                MemoryStreamDataSource infoDataSource = new MemoryStreamDataSource(infoBytes);
                m_zipFile.Add(infoDataSource, m_appDirectoryPath + InfoFileName);

                codeResources.UpdateFileHash(InfoFileName, infoBytes);
            }

            byte[] codeResourcesBytes = codeResources.GetBytes();
            MemoryStreamDataSource codeResourcesDataSource = new MemoryStreamDataSource(codeResourcesBytes);

            m_zipFile.Add(codeResourcesDataSource, m_appDirectoryPath + CodeResourcesFilePath);

            m_zipFile.CommitUpdate();
        }
Beispiel #2
0
        public void CompressDataInToFile(string directory, string password, string outputFile)
        {
            var fullFileListing = Directory.EnumerateFiles(directory, "*.*", SearchOption.AllDirectories);
            var directories     = Directory.EnumerateDirectories(directory, "*", SearchOption.AllDirectories);

            _logger.Information("Creating ZIP File");
            using (var zip = new ZipFile(outputFile))
            {
                zip.UseZip64 = UseZip64.On;

                _logger.Information("Adding directories..");
                foreach (var childDirectory in directories)
                {
                    _logger.Information(string.Format("Adding {0}", childDirectory.Replace(directory, string.Empty)));
                    zip.BeginUpdate();
                    zip.AddDirectory(childDirectory.Replace(directory, string.Empty));
                    zip.CommitUpdate();
                }

                _logger.Information("Adding files..");
                foreach (var file in fullFileListing)
                {
                    _logger.Information(string.Format("Adding {0}", file.Replace(directory, string.Empty)));
                    zip.BeginUpdate();
                    zip.Add(file, file.Replace(directory, string.Empty));
                    zip.CommitUpdate();
                }

                _logger.Information("Setting password..");
                zip.BeginUpdate();
                zip.Password = password;
                zip.CommitUpdate();
            }
        }
        public string StoreMeta(JObject meta)
        {
            var path = $"{_id}/{ArchiveSession.SessionFileName}";

            var ms = new MemoryStream();

            var writer     = new StreamWriter(ms);
            var jsonWriter = new JsonTextWriter(writer);
            var serializer = new JsonSerializer();

            serializer.Serialize(jsonWriter, meta);
            jsonWriter.Flush();


            ms.Position = 0;

            _zipFile.BeginUpdate();

            var ss = new StreamSource(ms);

            _zipFile.Add(ss, path, CompressionMethod.Stored);

            _zipFile.CommitUpdate();
            ms.Close();

            return(path);
        }
Beispiel #4
0
        /// <summary>
        /// Serializes and optionally encrypts the certificate authority files.
        /// </summary>
        /// <param name="key">The optional AES encryption key generated by <see cref="GenerateKey"/>.</param>
        /// <returns>The ZIP archive bytes.</returns>
        public byte[] ToZipBytes(string key = null)
        {
            if (updated)
            {
                zip.CommitUpdate();
            }

            return(stream.ToArray());
        }
Beispiel #5
0
 public void CreateDirectory(string directory)
 {
     if (FileInitialized() == false)
     {
         CreatePackage();
     }
     _zipFile.BeginUpdate();
     _zipFile.AddDirectory(directory);
     _zipFile.CommitUpdate();
 }
        public void Save(string a_path, byte[] a_asset)
        {
            m_package.BeginUpdate();

            PackageDataSource packageDataSource = new PackageDataSource(a_asset);

            m_package.Add(packageDataSource, a_path);

            m_package.CommitUpdate();
        }
Beispiel #7
0
 public void ZipDown(string zipname)
 {
     byte[] array = null;
     file.CommitUpdate();
     array       = new byte[ms.Length];
     ms.Position = 0L;
     ms.Read(array, 0, array.Length);
     HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + zipname);
     HttpContext.Current.Response.BinaryWrite(array);
     HttpContext.Current.Response.Flush();
     HttpContext.Current.Response.End();
 }
        public void AddAndDeleteEntries()
        {
            string tempFile = GetTempFilePath();

            Assert.IsNotNull(tempFile, "No permission to execute this test?");

            string addFile = Path.Combine(tempFile, "a.dat");

            MakeTempFile(addFile, 1);

            string addFile2 = Path.Combine(tempFile, "b.dat");

            MakeTempFile(addFile2, 259);

            string addDirectory = Path.Combine(tempFile, "dir");

            tempFile = Path.Combine(tempFile, "SharpZipTest.Zip");

            using (ZipFile f = ZipFile.Create(tempFile))
            {
                f.BeginUpdate();
                f.Add(addFile);
                f.Add(addFile2);
                f.AddDirectory(addDirectory);
                f.CommitUpdate();
                Assert.IsTrue(f.TestArchive(true));
            }

            using (ZipFile f = new ZipFile(tempFile))
            {
                Assert.AreEqual(3, f.Count);
                Assert.IsTrue(f.TestArchive(true));

                // Delete file
                f.BeginUpdate();
                f.Delete(f[0]);
                f.CommitUpdate();
                Assert.AreEqual(2, f.Count);
                Assert.IsTrue(f.TestArchive(true));

                // Delete directory
                f.BeginUpdate();
                f.Delete(f[1]);
                f.CommitUpdate();
                Assert.AreEqual(1, f.Count);
                Assert.IsTrue(f.TestArchive(true));
            }

            File.Delete(addFile);
            File.Delete(addFile2);
            File.Delete(tempFile);
        }
        /// <summary>
        /// Commits the updates.
        /// </summary>
        /// <remarks>Documented by Dev03, 2009-07-20</remarks>
        public void CommitUpdates()
        {
            ZipFile zipFile = null;

            try
            {
                zipFile          = new ZipFile(file.FullName);
                zipFile.UseZip64 = UseZip64.Off;  // AAB-20090720: Zip64 caused some problem when modifing the archive (ErrorReportHandler.cs) - Zip64 is required to bypass the 4.2G limitation of the original Zip format (http://en.wikipedia.org/wiki/ZIP_(file_format))

                ZipEntry errorReport = zipFile.GetEntry(Resources.ERRORFILE_NAME);

                MemoryStream stream = new MemoryStream();
                using (Stream s = GetZipStream(errorReport, zipFile))
                {
                    XmlDocument doc = new XmlDocument();
                    using (StreamReader reader = new StreamReader(s, Encoding.Unicode))
                    {
                        doc.LoadXml(reader.ReadToEnd());
                    }
                    foreach (Dictionary <string, string> value in values)
                    {
                        XmlElement xE = doc.CreateElement(value["nodeName"]);
                        xE.InnerText = value["value"].Trim();
                        XmlNode parentNode = doc.SelectSingleNode(value["parentPath"]);
                        if (parentNode == null)
                        {
                            return;
                        }
                        parentNode.AppendChild(xE);
                    }
                    doc.Save(stream);
                }
                ZipData data = new ZipData(stream);
                zipFile.BeginUpdate();
                zipFile.Delete(errorReport);    //delete first!
                zipFile.CommitUpdate();
                zipFile.BeginUpdate();
                zipFile.Add(data, errorReport.Name);
                zipFile.CommitUpdate();
            }
            finally
            {
                if (zipFile != null)
                {
                    zipFile.Close();
                }
            }
        }
Beispiel #10
0
 public override void Save(string tvOutputFile)
 {
     if (tvOutputFile != this.FileName)
     {
         File.Copy(this.FileName, tvOutputFile, true);
         this.FileName = tvOutputFile;
     }
     using (ZipFile zip = new ZipFile(tvOutputFile))
     {
         zip.BeginUpdate();
         this.SaveChannels(zip, "map-AirA", this.avbtChannels, this.avbtFileContent);
         this.SaveChannels(zip, "map-CableA", this.avbcChannels, this.avbcFileContent);
         this.SaveChannels(zip, "map-AirCableMixedA", this.avbxChannels, this.avbxFileContent);
         this.SaveChannels(zip, "map-AirD", this.dvbtChannels, this.dvbtFileContent);
         this.SaveChannels(zip, "map-CableD", this.dvbcChannels, this.dvbcFileContent);
         this.SaveChannels(zip, "map-AirCableMixedD", this.dvbxChannels, this.dvbxFileContent);
         this.SaveChannels(zip, "map-SateD", this.dvbsChannels, this.dvbsFileContent);
         this.SaveChannels(zip, "map-AstraHDPlusD", this.hdplusChannels, this.hdplusFileContent);
         this.SaveChannels(zip, "map-CablePrime_D", this.primeChannels, this.primeFileContent);
         this.SaveChannels(zip, "map-FreesatD", this.freesatChannels, this.freesatFileContent);
         this.SaveChannels(zip, "map-TivusatD", this.tivusatChannels, this.tivusatFileContent);
         this.SaveChannels(zip, "map-CanalDigitalSatD", this.canalDigitalChannels, this.canalDigitalFileContent);
         this.SaveChannels(zip, "map-DigitalPlusD", this.digitalPlusChannels, this.digitalPlusFileContent);
         this.SaveChannels(zip, "map-CyfraPlusD", this.cyfraPlusChannels, this.cyfraPlusFileContent);
         zip.CommitUpdate();
     }
 }
Beispiel #11
0
 internal static void AddFileToZip(string zipFilename, string fileToAdd, string storeAsName = null)
 {
     ZipStrings.CodePage = Encoding.UTF8.CodePage;
     // TODO: verify the new code above is working, otherwise restore this: -> ZipConstants.DefaultCodePage = System.Text.Encoding.UTF8.CodePage;
     if (!File.Exists(zipFilename))
     {
         FileStream zfs = File.Create(zipFilename);
         ZipOutputStream zipStream = new ZipOutputStream(zfs);
         zipStream.SetLevel(3); //0-9, 9 being the highest level of compression
         /*
         // NOTE: commented code because this is raising an error "Extra data extended Zip64 information length is invalid"
         // For compatibility with previous HG, we add the "[Content_Types].xml" file
         zipStream.PutNextEntry(new ZipEntry("[Content_Types].xml"));
         using (FileStream streamReader = File.OpenRead(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "[Content_Types].xml"))) {
             StreamUtils.Copy(streamReader, zipStream, new byte[4096]);
         }
         zipStream.CloseEntry();
         */
         zipStream.IsStreamOwner = true; // Makes the Close also close the underlying stream
         zipStream.Close();
     }
     ZipFile zipFile = new ZipFile(zipFilename);
     zipFile.BeginUpdate();
     zipFile.Add(fileToAdd, (String.IsNullOrWhiteSpace(storeAsName) ? fileToAdd : storeAsName));
     zipFile.CommitUpdate();
     zipFile.IsStreamOwner = true;
     zipFile.Close();
 }
Beispiel #12
0
        private void CompressFiles(XmlDocument needfiles)
        {
            DateTime start = DateTime.Now;

            string zip_file = Path.GetTempFileName();

            ZipFile zip = ZipFile.Create(zip_file);

            zip.BeginUpdate();

            foreach (XmlElement xe in needfiles.SelectNodes("//filelist/file"))
            {
                string file = Path.Combine(BaseDirectory, xe.InnerText);
                zip.Add(file, xe.GetAttribute("id"));
            }

            zip.CommitUpdate();
            zip.Close();

            Console.WriteLine("zip: " + DateTime.Now.Subtract(start).ToString());

            start = DateTime.Now;

            string url = string.Format("/session/{0}/files", ID);

            Connection.HttpPostFile(url, zip_file);
            File.Delete(zip_file);
            Console.WriteLine("zip send: " + DateTime.Now.Subtract(start).ToString());
        }
Beispiel #13
0
        public static void EnsureArchiveUpToDate(string baseCacheDirectory, ZipFile archive, HashSet <Hash128> entries)
        {
            List <string> filesToDelete = new List <string>();

            archive.BeginUpdate();

            foreach (Hash128 hash in entries)
            {
                string cacheTempFilePath = GenCacheTempFilePath(baseCacheDirectory, hash);

                if (File.Exists(cacheTempFilePath))
                {
                    string cacheHash = $"{hash}";

                    ZipEntry entry = archive.GetEntry(cacheHash);

                    if (entry != null)
                    {
                        archive.Delete(entry);
                    }

                    // We enforce deflate compression here to avoid possible incompatibilities on older version of Ryujinx that use System.IO.Compression.
                    archive.Add(new StaticDiskDataSource(cacheTempFilePath), cacheHash, CompressionMethod.Deflated);
                    filesToDelete.Add(cacheTempFilePath);
                }
            }

            archive.CommitUpdate();

            foreach (string filePath in filesToDelete)
            {
                File.Delete(filePath);
            }
        }
Beispiel #14
0
        /// <summary>
        /// Nén file
        /// </summary>
        /// <param name="zipFileName">Tên file sau khi nén</param>
        /// <param name="fileToZip">Mảng file cần nén</param>
        /// <param name="comment">Ghi chú file nén</param>
        public void DoZipFile(string zipFileName, FileSystemInfo[] fileToZip, string comment)
        {
            ZipFile zip = ZipFile.Create(zipFileName);

            try
            {
                zip.BeginUpdate();
                GetFilesToZip(fileToZip, zip);
                if (!string.IsNullOrEmpty(comment))
                {
                    zip.SetComment(comment);
                }
                zip.CommitUpdate();
                //zip.TestArchive(true);
                zip.Close();
            }
            catch
            {
                throw;
            }
            finally
            {
                zip.Close();
            }
        }
Beispiel #15
0
        public override void Save(string tvOutputFile)
        {
            if (tvOutputFile != this.FileName)
            {
                File.Copy(this.FileName, tvOutputFile);
                this.FileName = tvOutputFile;
            }

            using (var zip = new ZipFile(this.FileName))
            {
                zip.BeginUpdate();

                foreach (var channelList in this.DataRoot.ChannelLists)
                {
                    var dbPath = this.dbPathByChannelList[channelList];
                    SaveChannelList(channelList, dbPath);

                    var entryName = Path.GetFileName(dbPath);
                    zip.Delete(entryName);
                    zip.Add(dbPath, entryName);
                }

                zip.CommitUpdate();
            }
        }
Beispiel #16
0
        private Func <IRandomAccessStream, IAsyncOperation <bool> > WriteZipEntry(ZipFile zipFile)
        {
            return((stream) => AsyncInfo.Run((cancellationToken) => Task.Run(() =>
            {
                var hFile = NativeFileOperationsHelper.OpenFileForRead(ContainerPath, true);
                if (hFile.IsInvalid)
                {
                    return true;
                }
                try
                {
                    var znt = new ZipNameTransform(ContainerPath);
                    var zipDesiredName = znt.TransformFile(Path);
                    var entry = zipFile.GetEntry(zipDesiredName);

                    zipFile.BeginUpdate(new MemoryArchiveStorage(FileUpdateMode.Direct));
                    if (entry != null)
                    {
                        zipFile.Delete(entry);
                    }
                    zipFile.Add(new StreamDataSource(stream), zipDesiredName);
                    zipFile.CommitUpdate();
                }
                catch (Exception ex)
                {
                    App.Logger.Warn(ex, "Error writing zip file");
                }
                return true;
            })));
        }
Beispiel #17
0
        public void BasicEncryption()
        {
            const string TestValue = "0001000";
            var          memStream = new MemoryStream();

            using (ZipFile f = new ZipFile(memStream)) {
                f.IsStreamOwner = false;
                f.Password      = "******";

                var m = new StringMemoryDataSource(TestValue);
                f.BeginUpdate(new MemoryArchiveStorage());
                f.Add(m, "a.dat");
                f.CommitUpdate();
                Assert.IsTrue(f.TestArchive(true), "Archive test should pass");
            }

            using (ZipFile g = new ZipFile(memStream)) {
                g.Password = "******";
                ZipEntry ze = g[0];

                Assert.IsTrue(ze.IsCrypted, "Entry should be encrypted");
                using (StreamReader r = new StreamReader(g.GetInputStream(0))) {
                    string data = r.ReadToEnd();
                    Assert.AreEqual(TestValue, data);
                }
            }
        }
Beispiel #18
0
        public void Zip64Entries()
        {
            string tempFile = GetTempFilePath();

            Assert.IsNotNull(tempFile, "No permission to execute this test?");

            const int target = 65537;

            using (ZipFile zipFile = ZipFile.Create(Path.GetTempFileName()))
            {
                zipFile.BeginUpdate();

                for (int i = 0; i < target; ++i)
                {
                    ZipEntry ze = new ZipEntry(i.ToString());
                    ze.CompressedSize = 0;
                    ze.Size           = 0;
                    zipFile.Add(ze);
                }
                zipFile.CommitUpdate();

                Assert.IsTrue(zipFile.TestArchive(true));
                Assert.AreEqual(target, zipFile.Count, "Incorrect number of entries stored");
            }
        }
Beispiel #19
0
        public void UpdateZipInMemory(Stream zipStream, Stream entryStream, String entryName)
        {
            // The zipStream is expected to contain the complete zipfile to be updated
            ZipFile zipFile = new ZipFile(zipStream);

            zipFile.BeginUpdate();

            // To use the entryStream as a file to be added to the zip,
            // we need to put it into an implementation of IStaticDataSource.
            CustomStaticDataSource sds = new CustomStaticDataSource();

            sds.SetStream(entryStream);

            // If an entry of the same name already exists, it will be overwritten; otherwise added.
            zipFile.Add(sds, entryName);

            // Both CommitUpdate and Close must be called.
            zipFile.CommitUpdate();
            // Set this so that Close does not close the memorystream
            zipFile.IsStreamOwner = false;
            zipFile.Close();

            // Reposition to the start for the convenience of the caller.
            zipStream.Position = 0;
        }
Beispiel #20
0
        public void Zip64Useage()
        {
            var memStream = new MemoryStream();

            using (ZipFile f = new ZipFile(memStream)) {
                f.IsStreamOwner = false;
                f.UseZip64      = UseZip64.On;

                var m = new StringMemoryDataSource("0000000");
                f.BeginUpdate(new MemoryArchiveStorage());
                f.Add(m, "a.dat");
                f.Add(m, "b.dat");
                f.CommitUpdate();
                Assert.IsTrue(f.TestArchive(true));
            }

            byte[] rawArchive = memStream.ToArray();

            byte[] pseudoSfx = new byte[1049 + rawArchive.Length];
            Array.Copy(rawArchive, 0, pseudoSfx, 1049, rawArchive.Length);

            memStream = new MemoryStream(pseudoSfx);
            using (ZipFile f = new ZipFile(memStream)) {
                for (int index = 0; index < f.Count; ++index)
                {
                    Stream entryStream = f.GetInputStream(index);
                    var    data        = new MemoryStream();
                    StreamUtils.Copy(entryStream, data, new byte[128]);
                    string contents = Encoding.ASCII.GetString(data.ToArray());
                    Assert.AreEqual("0000000", contents);
                }
            }
        }
Beispiel #21
0
        public void UpdateCommentOnlyInMemory()
        {
            var ms = new MemoryStream();

            using (ZipFile testFile = new ZipFile(ms)) {
                testFile.IsStreamOwner = false;
                testFile.BeginUpdate();
                testFile.Add(new StringMemoryDataSource("Aha"), "No1", CompressionMethod.Stored);
                testFile.Add(new StringMemoryDataSource("And so it goes"), "No2", CompressionMethod.Stored);
                testFile.Add(new StringMemoryDataSource("No3"), "No3", CompressionMethod.Stored);
                testFile.CommitUpdate();

                Assert.IsTrue(testFile.TestArchive(true));
            }

            using (ZipFile testFile = new ZipFile(ms)) {
                Assert.IsTrue(testFile.TestArchive(true));
                Assert.AreEqual("", testFile.ZipFileComment);
                testFile.IsStreamOwner = false;

                testFile.BeginUpdate();
                testFile.SetComment("Here is my comment");
                testFile.CommitUpdate();

                Assert.IsTrue(testFile.TestArchive(true));
            }

            using (ZipFile testFile = new ZipFile(ms)) {
                Assert.IsTrue(testFile.TestArchive(true));
                Assert.AreEqual("Here is my comment", testFile.ZipFileComment);
            }
        }
Beispiel #22
0
        public void UnicodeNames()
        {
            var memStream = new MemoryStream();

            using (ZipFile f = new ZipFile(memStream)) {
                f.IsStreamOwner = false;

                f.BeginUpdate(new MemoryArchiveStorage());

                var names = new string[]
                {
                    "\u030A\u03B0",                         // Greek
                    "\u0680\u0685"                          // Arabic
                };

                foreach (string name in names)
                {
                    f.Add(new StringMemoryDataSource("Hello world"), name,
                          CompressionMethod.Deflated, true);
                }
                f.CommitUpdate();
                Assert.IsTrue(f.TestArchive(true));

                foreach (string name in names)
                {
                    int index = f.FindEntry(name, true);

                    Assert.IsTrue(index >= 0);
                    ZipEntry found = f[index];
                    Assert.AreEqual(name, found.Name);
                }
            }
        }
Beispiel #23
0
        public void Crypto_AddEncryptedEntryToExistingArchiveDirect()
        {
            var ms = new MemoryStream();

            using (ZipFile testFile = new ZipFile(ms)) {
                testFile.IsStreamOwner = false;
                testFile.BeginUpdate();
                testFile.Add(new StringMemoryDataSource("Aha"), "No1", CompressionMethod.Stored);
                testFile.Add(new StringMemoryDataSource("And so it goes"), "No2", CompressionMethod.Stored);
                testFile.Add(new StringMemoryDataSource("No3"), "No3", CompressionMethod.Stored);
                testFile.CommitUpdate();

                Assert.IsTrue(testFile.TestArchive(true));
            }

            using (ZipFile testFile = new ZipFile(ms)) {
                Assert.IsTrue(testFile.TestArchive(true));
                testFile.IsStreamOwner = true;

                testFile.BeginUpdate();
                testFile.Password = "******";
                testFile.Add(new StringMemoryDataSource("Zapata!"), "encrypttest.xml");
                testFile.CommitUpdate();

                Assert.IsTrue(testFile.TestArchive(true));

                int entryIndex = testFile.FindEntry("encrypttest.xml", true);
                Assert.IsNotNull(entryIndex >= 0);
                Assert.IsTrue(testFile[entryIndex].IsCrypted);
            }
        }
Beispiel #24
0
        void TryDeleting(byte[] master, int totalEntries, int additions, params string[] toDelete)
        {
            var ms = new MemoryStream();

            ms.Write(master, 0, master.Length);

            using (ZipFile f = new ZipFile(ms)) {
                f.IsStreamOwner = false;
                Assert.AreEqual(totalEntries, f.Count);
                Assert.IsTrue(f.TestArchive(true));
                f.BeginUpdate(new MemoryArchiveStorage());

                for (int i = 0; i < additions; ++i)
                {
                    f.Add(new StringMemoryDataSource("Another great file"),
                          string.Format("Add{0}.dat", i + 1));
                }

                foreach (string name in toDelete)
                {
                    f.Delete(name);
                }
                f.CommitUpdate();

                // write stream to file to assist debugging.
                // WriteToFile(@"c:\aha.zip", ms.ToArray());

                int newTotal = totalEntries + additions - toDelete.Length;
                Assert.AreEqual(newTotal, f.Count,
                                string.Format("Expected {0} entries after update found {1}", newTotal, f.Count));
                Assert.IsTrue(f.TestArchive(true), "Archive test should pass");
            }
        }
Beispiel #25
0
        /// <summary>
        /// 往已存在的压缩文件里添加指定的文件列表,压缩文件不存在时,新建
        /// </summary>
        /// <param name="zipFilePath">要压缩到的文件路径名</param>
        /// <param name="files">要被压缩的文件列表</param>
        public static void AddFiles(string zipFilePath, params string[] files)
        {
            if (string.IsNullOrEmpty(zipFilePath))
            {
                zipFilePath = Path.GetFileName(files[0]) + ".zip";
            }

            if (!File.Exists(zipFilePath))
            {
                using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath)))
                {
                    s.Finish();
                    s.Close();
                }
            }
            using (ZipFile zip = new ZipFile(zipFilePath))
            {
                zip.BeginUpdate();
                //zip.IsStreamOwner = false;
                foreach (string file in files)
                {
                    zip.Add(file);
                }
                zip.CommitUpdate();
                zip.Close();
            }
        }
Beispiel #26
0
        private void ZipOneFile(string sourceFilePath, string entryName, string zipFilePath)
        {
            ZipFile?zipFile = null;

            try
            {
                zipFile = new ZipFile(File.Open(zipFilePath, FileMode.OpenOrCreate));
                zipFile.BeginUpdate();

                if (zipFile.FindEntry(entryName, false) < 0)
                {
                    zipFile.Add(sourceFilePath, entryName);
                }

                zipFile.CommitUpdate();
            }
            catch (Exception e)
            {
                this.EventLogger.LogEvent($"Failed to Zip the File {sourceFilePath}. Error {e.Message}");
                zipFile?.AbortUpdate();
            }
            finally
            {
                zipFile?.Close();
            }
        }
Beispiel #27
0
        private void RemoveCommonAutoLoadedMods(string path)
        {
            // List<string> itemsToRemove = new List<string>();
            using (ZipFile zf = new ZipFile(path))
            {
                zf.BeginUpdate();
                foreach (ZipEntry item in zf)
                {
                    if (ShouldDelete(item))
                    {
                        //   itemsToRemove.Add(item.Name);
                        zf.Delete(item);
                    }
                }
                zf.CommitUpdate();
            }
            //foreach (string item in itemsToRemove)
            //{
            //    using (ZipFile zf = new ZipFile(path))
            //    {



            //    }
            //}
        }
Beispiel #28
0
        private async Task ZipLogFileAsync(string strFileName, string strTempFileName)
        {
            string strZipPath = strFileName.Replace(".txt", ".zip");

            try
            {
                //Alte Datei wird gezipt, bevor die neue erstellt wird. Alte Textfile wird gelöscht
                if (File.Exists(strTempFileName))
                {
                    using (ZipFile zip = ZipFile.Create(strZipPath))
                    {
                        zip.NameTransform = new ZipNameTransform(m_LogDir.FullName);
                        zip.BeginUpdate();
                        zip.Add(strTempFileName, strFileName);
                        zip.CommitUpdate();
                    }

                    File.Delete(strTempFileName);
                }
            }
            catch (Exception ex)
            {
                //TODO: Error
            }

            await Task.Delay(1);
        }
Beispiel #29
0
        public void CreateEmptyArchive()
        {
            string tempFile = GetTempFilePath();

            Assert.IsNotNull(tempFile, "No permission to execute this test?");

            tempFile = Path.Combine(tempFile, "SharpZipTest.Zip");

            using (ZipFile f = ZipFile.Create(tempFile))
            {
                f.BeginUpdate();
                f.CommitUpdate();
                Assert.IsTrue(f.TestArchive(true));
                f.Close();
            }

            using (ZipFile f = new ZipFile(tempFile))
            {
                Assert.AreEqual(0, f.Count);
            }
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                store.DeleteFile(tempFile);
            }
        }
        /// <summary>
        /// 下载实现==批量打包
        /// 实现方式:stream(流)
        /// </summary>
        /// <param name="filesPath">被压缩文件的多文件路径</param>
        /// <param name="zipFileName">压缩包名称</param>
        private void download(List <string> filesPath, string zipFileName)
        {
            MemoryStream outms = new MemoryStream();//输出流

            byte[] buffer = null;

            //压缩
            using (ZipFile file = ZipFile.Create(outms))
            {
                file.BeginUpdate();
                file.NameTransform = new MyNameTransfom();
                foreach (string filepath in filesPath)
                {
                    file.Add(Server.MapPath(filepath));
                }

                file.CommitUpdate();
                buffer         = new byte[outms.Length];
                outms.Position = 0;
                outms.Read(buffer, 0, buffer.Length);
            }
            Response.ContentType = "application/octet-stream";
            //通知浏览器下载文件而不是打开
            Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlDecode(zipFileName));
            Response.BinaryWrite(buffer);
            Response.Flush();
            Response.End();
        }