UpdateEntry() public method

Updates the given entry in the ZipFile, using the given delegates to open and close the stream that provides the content for the ZipEntry.
Calling this method is equivalent to removing the ZipEntry for the given file name and directory path, if it exists, and then calling . See the documentation for that method for further explanation.
public UpdateEntry ( string entryName, OpenDelegate opener, CloseDelegate closer ) : ZipEntry
entryName string /// The name, including any path, to use within the archive for the entry. ///
opener OpenDelegate /// the delegate that will be invoked to open the stream ///
closer CloseDelegate /// the delegate that will be invoked to close the stream ///
return ZipEntry
Exemplo n.º 1
1
        public static string CompileNewXAP(HashSet<string> fullsetOfDlls, string shared)
        {
            var tempPath = Path.Combine(shared, Guid.NewGuid() + ".xap");
            using (
                var stream = Assembly.GetExecutingAssembly()
                                     .GetManifestResourceStream("sl_runner.xap.sl-50-xap.xap"))
            using (var baseZip = ZipFile.Read(stream))
            {
                var set = new HashSet<string>();
                var item = baseZip["AppManifest.xaml"];
                var xml = XDocument.Parse(new StreamReader(item.OpenReader()).ReadToEnd());
                using (
                    var zip = new ZipFile()
                    {
                        CompressionLevel = CompressionLevel.Default,
                        CompressionMethod = CompressionMethod.Deflate
                    })
                {
                    zip.AddEntry("AppManifest.xaml", new byte[] { });
                    foreach (var entry in baseZip.Entries)
                    {
                        if (entry.FileName.Contains(".dll"))
                        {
                            using (var memstream = new MemoryStream())
                            {
                                entry.OpenReader().CopyTo(memstream);
                                memstream.Seek(0, SeekOrigin.Begin);
                                zip.AddEntry(entry.FileName, memstream.ToArray());
                                set.Add(Path.GetFileName(entry.FileName));
                            }
                        }
                    }
                    var desc = xml.DescendantNodes().OfType<XElement>();

                    var parts = desc.Single(it => it.Name.LocalName.Contains("Deployment.Parts"));

                    foreach (var dll in fullsetOfDlls)
                    {
                        if (set.Contains(Path.GetFileName(dll)))
                            continue;
                        set.Add(Path.GetFileName(dll));
                        zip.AddFile(dll, "");
                        parts.Add(new XElement(XName.Get("AssemblyPart", "http://schemas.microsoft.com/client/2007/deployment"),
                                               new XAttribute(
                                                   XName.Get("Name", "http://schemas.microsoft.com/winfx/2006/xaml"),
                                                   Path.GetFileNameWithoutExtension(dll)),
                                               new XAttribute("Source", Path.GetFileName(dll))));
                    }
                    using (var memstream = new MemoryStream())
                    {
                        xml.Save(memstream, SaveOptions.OmitDuplicateNamespaces);
                        zip.UpdateEntry("AppManifest.xaml", memstream.ToArray());
                    }
                    zip.Save(tempPath);
                }
            }
            return tempPath;
        }
        public void UpdateMission(ZkDataContext db, Mission mission, Mod modInfo) {
            var file = mission.Mutator.ToArray();
            var tempName = Path.GetTempFileName() + ".zip";
            File.WriteAllBytes(tempName, file);

            using (var zf = new ZipFile(tempName))
            {
                zf.UpdateEntry("modinfo.lua", Encoding.UTF8.GetBytes(GetModInfo(mission.NameWithVersion, mission.Mod, mission.Name, "ZK")));    // FIXME hardcoded crap
                FixScript(mission, zf, "script.txt");
                var script = FixScript(mission, zf, GlobalConst.MissionScriptFileName);
                modInfo.MissionScript = script;
                //modInfo.ShortName = mission.Name;
                modInfo.Name = mission.NameWithVersion;
                zf.Save();
            }
            mission.Mutator = File.ReadAllBytes(tempName);
            mission.Script = Regex.Replace(mission.Script, "GameType=([^;]+);", (m) => { return string.Format("GameType={0};", mission.NameWithVersion); });
            
            File.Delete(tempName);
            
            var resource = db.Resources.FirstOrDefault(x => x.MissionID == mission.MissionID); 
            if (resource == null)
            {
                resource = new Resource() { DownloadCount = 0, TypeID = ZkData.ResourceType.Mod };
                db.Resources.Add(resource);
            }
            resource.InternalName = mission.NameWithVersion;
            resource.MissionID = mission.MissionID;

            resource.ResourceDependencies.Clear();
            resource.ResourceDependencies.Add(new ResourceDependency() { NeedsInternalName = mission.Map });
            resource.ResourceDependencies.Add(new ResourceDependency() { NeedsInternalName = mission.Mod });
            resource.ResourceContentFiles.Clear();
            

            // generate torrent
            var tempFile = Path.Combine(Path.GetTempPath(), mission.SanitizedFileName);
            File.WriteAllBytes(tempFile, mission.Mutator.ToArray());
            var creator = new TorrentCreator();
            creator.Path = tempFile;
            var torrentStream = new MemoryStream();
            creator.Create(torrentStream);
            try
            {
                File.Delete(tempFile);
            }
            catch { }

            var md5 = Hash.HashBytes(mission.Mutator.ToArray()).ToString();
            resource.ResourceContentFiles.Add(new ResourceContentFile()
            {
                FileName = mission.SanitizedFileName,
                Length = mission.Mutator.Length,
                LinkCount = 1,
                Links = string.Format(MissionFileUrl, mission.MissionID),
                Md5 = md5
            });


            var basePath = GlobalConst.SiteDiskPath + @"\resources\";
            File.WriteAllBytes(string.Format(@"{2}\{0}_{1}.torrent", resource.InternalName.EscapePath(), md5, basePath), torrentStream.ToArray());
            
            File.WriteAllBytes(string.Format(@"{1}\{0}.metadata.xml.gz", resource.InternalName.EscapePath(), basePath),
                                   MetaDataCache.SerializeAndCompressMetaData(modInfo));
            
            File.WriteAllBytes(string.Format(GlobalConst.SiteDiskPath + @"\img\missions\{0}.png", mission.MissionID, basePath), mission.Image.ToArray());

        }
 static string FixScript(Mission mission, ZipFile zf, string scriptName)
 {
     var ms = new MemoryStream();
     zf[scriptName].Extract(ms);
     var script = Encoding.UTF8.GetString(ms.ToArray());
     script = Regex.Replace(script, "GameType=([^;]+);", (m) => { return string.Format("GameType={0};", mission.NameWithVersion); });
     zf.UpdateEntry(scriptName, Encoding.UTF8.GetBytes(script));
     return script;
 }
Exemplo n.º 4
0
        public void JitStream_Update_wi13899()
        {
            int fileCount = 12 + _rnd.Next(16);
            string dirToZip = "fodder";
            var files = TestUtilities.GenerateFilesFlat(dirToZip, fileCount, 100, 72000);
            OpenDelegate opener = (name) =>
                {
                    TestContext.WriteLine("Opening {0}", name);
                    Stream s = File.OpenRead(Path.Combine(dirToZip,name));
                    return s;
                };

            CloseDelegate closer = (e, s) =>
                {
                    TestContext.WriteLine("Closing {0}", e);
                    s.Dispose();
                };

            // Two passes: first to call UpdateEntry() when no prior entry exists.
            // Second to call UpdateEntry when a prior entry exists.
            for (int j=0; j < 2; j++)
            {
                string zipFileToCreate = String.Format("wi13899-{0}.zip", j);

                TestContext.WriteLine("");
                TestContext.WriteLine("Creating zipfile {0}", zipFileToCreate);
                if (j!=0)
                {
                    using (var zip = new ZipFile(zipFileToCreate))
                    {
                        foreach (var file in files)
                        {
                            zip.AddEntry(Path.GetFileName(file), "This is the content for file " + file);
                        }
                        zip.Save();
                    }

                    Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate),
                                         files.Length);

                    BasicVerifyZip(zipFileToCreate);

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

                using (var zip = new ZipFile(zipFileToCreate))
                {
                    foreach (var file in files)
                    {
                        zip.UpdateEntry(Path.GetFileName(file), opener, closer);
                    }
                    zip.Save();
                }

                BasicVerifyZip(zipFileToCreate);
                // verify checksum here?
            }
        }
Exemplo n.º 5
0
        private void AddToZip(string name, byte[] data)
        {
            using (var file = new ZipFile(_zipFile))
              {
            if (file.ContainsEntry(name))
            {
              file.UpdateEntry(name, data);
            }
            else
            {
              file.AddEntry(name, data);
            }

            file.Save();
              }
        }
 /// <summary>
 ///     Updating the current version string in storage.
 /// </summary>
 /// <param name="zip"><see cref="ZipFile" /> to store the version string in.</param>
 private void UpdateVersion(ZipFile zip)
 {
     zip.UpdateEntry(VersionFile, GameVersion);
 }
        /// <summary>
        ///     Copy a file entry inside a <see cref="ZipFile" />.
        /// </summary>
        /// <param name="zip"><see cref="ZipFile" /> on which to perform the operation.</param>
        /// <param name="source">Source file name to copy.</param>
        /// <param name="target">Destination file name for the copy.</param>
        private static void ZipCopy(ZipFile zip, string source, string target)
        {
            var entry = zip[source];

            byte[] buffer;
            using (var s = entry.OpenReader()) {
                using (var ms = new MemoryStream()) {
                    s.CopyTo(ms);
                    buffer = ms.ToArray();
                }
            }

            zip.UpdateEntry(target, buffer);
        }
        /// <summary>
        ///     Store a <see cref="UpdateReport" /> in a <see cref="ZipFile" />.
        /// </summary>
        /// <param name="zip"><see cref="ZipFile" /> to write to.</param>
        /// <param name="report"><see cref="UpdateReport" /> to store.</param>
        private static void StoreReport(ZipFile zip, UpdateReport report)
        {
            var textTarget = string.Format(UpdateReportTextFile, report.PreviousVersion, report.UpdateVersion);
            zip.UpdateEntry(textTarget, string.Join(Environment.NewLine, report.Changes.Select(_ => _.ToString())),
                ZipEncoding);

            var yamlTarget = string.Format(UpdateReportYamlFile, report.PreviousVersion, report.UpdateVersion);
            var serializer = new Serializer();
            byte[] yamlBuffer;
            using (var ms = new MemoryStream()) {
                using (TextWriter writer = new StreamWriter(ms, ZipEncoding)) {
                    serializer.Serialize(writer, report);
                    writer.Flush();
                    yamlBuffer = ms.ToArray();
                }
            }
            zip.UpdateEntry(yamlTarget, yamlBuffer);

            var binTarget = string.Format(UpdateReportBinFile, report.PreviousVersion, report.UpdateVersion);
            var formatter = new BinaryFormatter();
            byte[] binBuffer;

            using (var ms = new MemoryStream()) {
                formatter.Serialize(ms, report);
                binBuffer = ms.ToArray();
            }

            zip.UpdateEntry(binTarget, binBuffer);
        }
 /// <summary>
 ///     Serialize a <see cref="RelationDefinition" /> into a <see cref="ZipFile" />.
 /// </summary>
 /// <param name="zip"><see cref="ZipFile" /> to write to.</param>
 /// <param name="definition"><see cref="RelationDefinition" /> to store.</param>
 /// <param name="path">File name inside the storage to write to.</param>
 private static void StoreDefinition(ZipFile zip, RelationDefinition definition, string path)
 {
     using (var ms = new MemoryStream()) {
         using (var writer = new StreamWriter(ms, ZipEncoding)) {
             definition.Serialize(writer);
             writer.Flush();
             zip.UpdateEntry(path, ms.ToArray());
         }
     }
 }
Exemplo n.º 10
0
		private static void UpdateXmlEntity(ZipEntry entry, string selector, Action<XElement> update, ZipFile zip, IXmlNamespaceResolver nsResolver)
		{
			var output = new MemoryStream();
			using (var entryStream = entry.OpenReader())
			{
				var xml = XDocument.Load(entryStream);
				update(xml.XPathSelectElement(selector, nsResolver));
				xml.Save(output);
			}
			zip.UpdateEntry(entry.FileName, output.GetBuffer());
			zip.Save();
		}
Exemplo n.º 11
0
        public void Update_MultipleSaves_wi10319()
        {
            string zipFileToCreate = "MultipleSaves_wi10319.zip";

            using (ZipFile _zipFile = new ZipFile())
            {
                using (MemoryStream data = new MemoryStream())
                {
                    using (StreamWriter writer = new StreamWriter(data))
                    {
                        writer.Write("Dit is een test string.");
                        writer.Flush();

                        data.Seek(0, SeekOrigin.Begin);
                        _zipFile.AddEntry("test.txt", data);
                        _zipFile.Save(zipFileToCreate);
                        _zipFile.AddEntry("test2.txt", "Esta es un string de test");
                        _zipFile.Save(zipFileToCreate);
                        _zipFile.AddEntry("test3.txt", "this is some content for the entry.");
                        _zipFile.Save(zipFileToCreate);
                    }
                }
            }

            using (ZipFile _zipFile = FileSystemZip.Read(zipFileToCreate))
            {
                using (MemoryStream data = new MemoryStream())
                {
                    using (StreamWriter writer = new StreamWriter(data))
                    {
                        writer.Write("Dit is een andere test string.");
                        writer.Flush();

                        data.Seek(0, SeekOrigin.Begin);

                        _zipFile.UpdateEntry("test.txt", data);
                        _zipFile.Save(zipFileToCreate);
                        _zipFile.UpdateEntry("test2.txt", "Esta es un otro string de test");
                        _zipFile.Save(zipFileToCreate);
                        _zipFile.UpdateEntry("test3.txt", "This is another string for content.");
                        _zipFile.Save(zipFileToCreate);

                    }
                }
            }
        }
Exemplo n.º 12
0
		private static void UpdateCsFiles(ZipEntry entry, string slideId, ZipFile zip)
		{
			string code;
			using (var entryStream = entry.OpenReader())
			{
				code = new StreamReader(entryStream).ReadToEnd();
			}
			code = Regex.Replace(code, "(?<=\\[Slide\\(\".*\",\\s*\").+(?=\"\\)\\])", slideId);
			zip.UpdateEntry(entry.FileName, code, Encoding.UTF8);
			zip.Save();
		}
Exemplo n.º 13
0
 public void UpdateDatabaseInZip(string zipFilePath, string dbFilePath)
 {
     _log.Info("Updating database in zip");
     using (var zipFile = new ZipFile(zipFilePath)) {
         var existingZip = zipFile.SelectEntries("name = *.bak").FirstOrDefault();
         if (existingZip != null) {
             using (var dbStream = new FileStream(dbFilePath, FileMode.Open)) {
                 zipFile.UpdateEntry(existingZip.FileName, dbStream);
             }
         }
         zipFile.Save();
         _log.DebugFormat("Database updated in {0} from {1}", zipFilePath, dbFilePath);
     }
 }
Exemplo n.º 14
0
        public void UpdateZip_UpdateItem_UpdateTwice()
        {
            string filename = "text.txt";
            string contentText1 = "Content 1";
            string contentText2 = "Content 2 - this is longer";

            // select the name of the zip file
            string zipFileToCreate = Path.Combine(TopLevelDir, "UpdateZip_UpdateItem_UpdateTwice.zip");

            // Create the zip file
            Directory.SetCurrentDirectory(TopLevelDir);
            using (ZipFile zip1 = new ZipFile())
            {
                var content1 = new MemoryStream(Encoding.Default.GetBytes(contentText1));
                var entry1 = zip1.UpdateEntry(filename, content1);
                Assert.IsNotNull(entry1);
                zip1.Comment = "UpdateTests::UpdateZip_UpdateItem_UpdateTwice(): This archive will be updated.";
                zip1.Save(zipFileToCreate);

                using (ZipFile zip2 = new ZipFile(zipFileToCreate))
                {
                    var entry = zip2[filename];
                    using (var ms = new MemoryStream())
                    {
                        entry.OpenReader().CopyTo(ms);
                        var content = Encoding.Default.GetString(ms.ToArray());
                        Assert.AreEqual(contentText1, content);
                    }
                }

                var content2 = new MemoryStream(Encoding.Default.GetBytes(contentText2));
                var entry2 = zip1.UpdateEntry(filename, content2);
                Assert.IsNotNull(entry2);
                zip1.Comment = "UpdateTests::UpdateZip_UpdateItem_UpdateTwice(): This archive was updated.";
                zip1.Save(zipFileToCreate);

                using (ZipFile zip3 = new ZipFile(zipFileToCreate))
                {
                    var entry = zip3[filename];
                    using (var ms = new MemoryStream())
                    {
                        entry.OpenReader().CopyTo(ms);
                        var content = Encoding.Default.GetString(ms.ToArray());
                        Assert.AreEqual(contentText2, content);
                    }
                }
            }
        }
Exemplo n.º 15
0
        public void UpdateZip_UpdateItem_UpdateMultipleTimesFromStream_SaveAsStream()
        {
            string filename = "text1.txt";
            string filename2 = "text2.txt";
            string contentText1 = "Content 1";
            string contentText2 = "Content 2 - this is longer";
            string contentText3 = "Content 3";

            // select the name of the zip file
            string zipFileToCreate = Path.Combine(TopLevelDir, "UpdateZip_UpdateItem_UpdateMultipleTimes.zip");
            string zipFileToSaveAs = Path.Combine(TopLevelDir, "UpdateZip_UpdateItem_UpdateMultipleTimes_New.zip");

            #region Create the zip file

            Directory.SetCurrentDirectory(TopLevelDir);
            using (ZipFile zipSave = new ZipFile())
            {
                var content1 = new MemoryStream(Encoding.Default.GetBytes(contentText1));
                var entry1 = zipSave.UpdateEntry(filename, content1);
                Assert.IsNotNull(entry1);

                var content2 = new MemoryStream(Encoding.Default.GetBytes(contentText2));
                var entry2 = zipSave.UpdateEntry(filename2, content2);
                Assert.IsNotNull(entry2);
                zipSave.Comment = "UpdateTests::UpdateZip_UpdateItem_UpdateMultipleTimes(): This archive will be updated.";
                zipSave.Save(zipFileToCreate);
            }
            using (ZipFile zipTest = new ZipFile(zipFileToCreate))
            {
                var entry = zipTest[filename];
                using (var ms = new MemoryStream())
                {
                    entry.OpenReader().CopyTo(ms);
                    var content = Encoding.Default.GetString(ms.ToArray());
                    Assert.AreEqual(contentText1, content);
                }
            }

            #endregion

            var zipData = File.ReadAllBytes(zipFileToCreate);
            var sourceStream = new MemoryStream(zipData);
            using (ZipFile zipSave = ZipFile.Read(sourceStream))
            {
                var content2 = new MemoryStream(Encoding.Default.GetBytes(contentText2));
                var entry2 = zipSave.UpdateEntry(filename, content2);
                Assert.IsNotNull(entry2);
                zipSave.Comment = "UpdateTests::UpdateZip_UpdateItem_UpdateMultipleTimes(): This archive was updated once.";

                var memoryStream = new MemoryStream(); //Attention: the source stream can't be disposed, as its needed to read not edited entries on the next save
                zipSave.Save(memoryStream);
                File.WriteAllBytes(zipFileToSaveAs, memoryStream.ToArray());
                Assert.IsTrue(ZipFile.CheckZip(zipFileToSaveAs));

                var content3 = new MemoryStream(Encoding.Default.GetBytes(contentText3));
                var entry3 = zipSave.UpdateEntry(filename, content3);
                Assert.IsNotNull(entry3);
                zipSave.Comment = "UpdateTests::UpdateZip_UpdateItem_UpdateMultipleTimes(): This archive was updated twice.";

                memoryStream = new MemoryStream();
                zipSave.Save(memoryStream);
                File.WriteAllBytes(zipFileToSaveAs, memoryStream.ToArray());
            }

            Assert.IsTrue(ZipFile.CheckZip(zipFileToSaveAs));
            using (ZipFile zipTest = new ZipFile(zipFileToSaveAs))
            {
                var entry = zipTest[filename];
                using (var ms = new MemoryStream())
                {
                    entry.OpenReader().CopyTo(ms);
                    var content = Encoding.Default.GetString(ms.ToArray());
                    Assert.AreEqual(contentText3, content);
                }
            }
        }
Exemplo n.º 16
0
        public void UpdateZip_UpdateItem_UpdateMultipleTimes_SaveAsTwice()
        {
            string filename = "text1.txt";
            string filename2 = "text2.txt";
            string contentText1 = "Content 1";
            string contentText2 = "Content 2 - this is longer";
            string contentText3 = "Content 3";

            // select the name of the zip file
            string zipFileToCreate = Path.Combine(TopLevelDir, "UpdateZip_UpdateItem_UpdateMultipleTimes.zip");
            string zipFileToSaveAs = Path.Combine(TopLevelDir, "UpdateZip_UpdateItem_UpdateMultipleTimes_New.zip");

            #region Create the zip file

            Directory.SetCurrentDirectory(TopLevelDir);
            using (ZipFile zipSave = new ZipFile())
            {
                var content1 = new MemoryStream(Encoding.Default.GetBytes(contentText1));
                var entry1 = zipSave.UpdateEntry(filename, content1);
                Assert.IsNotNull(entry1);

                var content2 = new MemoryStream(Encoding.Default.GetBytes(contentText2));
                var entry2 = zipSave.UpdateEntry(filename2, content2);
                Assert.IsNotNull(entry2);
                zipSave.Comment = "UpdateTests::UpdateZip_UpdateItem_UpdateMultipleTimes(): This archive will be updated.";
                zipSave.Save(zipFileToCreate);
            }
            using (ZipFile zipTest = new ZipFile(zipFileToCreate))
            {
                var entry = zipTest[filename];
                using (var ms = new MemoryStream())
                {
                    entry.OpenReader().CopyTo(ms);
                    var content = Encoding.Default.GetString(ms.ToArray());
                    Assert.AreEqual(contentText1, content);
                }
            }

            #endregion

            using (ZipFile zipSave = new ZipFile(zipFileToCreate))
            {
                var content2 = new MemoryStream(Encoding.Default.GetBytes(contentText2));
                var entry2 = zipSave.UpdateEntry(filename, content2);
                Assert.IsNotNull(entry2);
                zipSave.Comment = "UpdateTests::UpdateZip_UpdateItem_UpdateMultipleTimes(): This archive was updated once.";
                zipSave.Save(zipFileToSaveAs);

                Assert.IsTrue(ZipFile.CheckZip(zipFileToSaveAs));

                var content3 = new MemoryStream(Encoding.Default.GetBytes(contentText3));
                var entry3 = zipSave.UpdateEntry(filename, content3);
                Assert.IsNotNull(entry3);
                zipSave.Comment = "UpdateTests::UpdateZip_UpdateItem_UpdateMultipleTimes(): This archive was updated twice.";
                zipSave.Save(zipFileToSaveAs);
            }

            Assert.IsTrue(ZipFile.CheckZip(zipFileToSaveAs));
            using (ZipFile zipTest = new ZipFile(zipFileToSaveAs))
            {
                var entry = zipTest[filename];
                using (var ms = new MemoryStream())
                {
                    entry.OpenReader().CopyTo(ms);
                    var content = Encoding.Default.GetString(ms.ToArray());
                    Assert.AreEqual(contentText3, content);
                }
            }
        }