public AddEntry ( string entryName, OpenDelegate opener, CloseDelegate closer ) : |
||
entryName | string | the name of the entry to add |
opener | OpenDelegate | /// the delegate that will be invoked by ZipFile.Save() to get the /// readable stream for the given entry. ZipFile.Save() will call /// read on this stream to obtain the data for the entry. This data /// will then be compressed and written to the newly created zip /// file. /// |
closer | CloseDelegate | /// the delegate that will be invoked to close the stream. This may /// be null (Nothing in VB), in which case no call is makde to close /// the stream. /// |
리턴 |
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 Write(Stream stream) { using (ZipFile zip = new ZipFile()) { byte[] circledata = { (byte) 0x3c, (byte) 0x7e, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0x7e, (byte) 0x3c }; Image mask = Image.GetInstance(8, 8, 1, 1, circledata); mask.MakeMask(); mask.Inverted = true; ImageMask im = new ImageMask(); zip.AddEntry(RESULT1, im.CreatePdf(mask)); byte[] gradient = new byte[256]; for (int i = 0; i < 256; i++) { gradient[i] = (byte) i; } mask = Image.GetInstance(256, 1, 1, 8, gradient); mask.MakeMask(); im = new ImageMask(); zip.AddEntry(RESULT2, im.CreatePdf(mask)); zip.AddFile(RESOURCE, ""); zip.Save(stream); } }
/// <summary> /// Create a TOC from the chapters and create the file /// </summary> /// <param name="filename"></param> public void Save(string filename) { using (ZipFile zippedBook = new ZipFile()) { zippedBook.ForceNoCompression = true; ZipEntry mimetype = zippedBook.AddEntry("mimetype", "", "application/epub+zip"); zippedBook.ForceNoCompression = false; zippedBook.AddEntry("container.xml", "META-INF", GetResource("EPubLib.Files.META_INF.container.xml")); zippedBook.AddEntry("content.opf", "OEBPS", GetContentOpf(), Encoding.UTF8); zippedBook.AddEntry("toc.ncx", "OEBPS", GetToc(), Encoding.UTF8); foreach (Chapter chapter in GetChapters()) { zippedBook.AddEntry("chapter" + chapter.Number.ToString("000") + ".xhtml", "OEBPS", chapter.Content, Encoding.UTF8); } foreach (FileItem image in GetImages()) { zippedBook.AddEntry(image.Name, "OEBPS/images", image.Data); } zippedBook.Save(filename); } }
public void ImportActionShouldAddTestsToProblemIfZipFileIsCorrect() { var zipFile = new ZipFile(); var inputTest = "input"; var outputTest = "output"; zipFile.AddEntry("test.001.in.txt", inputTest); zipFile.AddEntry("test.001.out.txt", outputTest); var zipStream = new MemoryStream(); zipFile.Save(zipStream); zipStream = new MemoryStream(zipStream.ToArray()); this.File.Setup(x => x.ContentLength).Returns(1); this.File.Setup(x => x.FileName).Returns("file.zip"); this.File.Setup(x => x.InputStream).Returns(zipStream); var redirectResult = this.TestsController.Import("1", this.File.Object, false, false) as RedirectToRouteResult; Assert.IsNotNull(redirectResult); Assert.AreEqual("Problem", redirectResult.RouteValues["action"]); Assert.AreEqual(1, redirectResult.RouteValues["id"]); var tests = this.Data.Problems.All().First(pr => pr.Id == 1).Tests.Count; Assert.AreEqual(14, tests); var tempDataHasKey = this.TestsController.TempData.ContainsKey(GlobalConstants.InfoMessage); Assert.IsTrue(tempDataHasKey); var tempDataMessage = this.TestsController.TempData[GlobalConstants.InfoMessage]; Assert.AreEqual("Тестовете са добавени към задачата", tempDataMessage); }
public override void ExportImpl(System.Windows.Window parentWindow, Data.DataMatrix matrix, string datasetName, object options) { var opts = options as DarwinCoreExporterOptions; var columnNames = new List<String>(); matrix.Columns.ForEach(col => { if (!col.IsHidden) { columnNames.Add(col.Name); } }); datasetName = SystemUtils.StripIllegalFilenameChars(datasetName); using (ZipFile archive = new ZipFile(opts.Filename)) { archive.AddEntry(String.Format("{0}\\occurrence.txt", datasetName), (String name, Stream stream) => { ExportToCSV(matrix, stream, opts, true); }); archive.AddEntry(String.Format("{0}\\meta.xml", datasetName), (String name, Stream stream) => { WriteMetaXml(stream, opts, columnNames); }); archive.Save(); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { Stationery s = new Stationery(); StampStationery ss = new StampStationery(); byte[] stationery = s.CreateStationary(); byte[] sStationery = ss.ManipulatePdf( ss.CreatePdf(), stationery ); byte[] insertPages = ManipulatePdf(sStationery, stationery); zip.AddEntry(RESULT1, insertPages); // reorder the pages in the PDF PdfReader reader = new PdfReader(insertPages); reader.SelectPages("3-41,1-2"); using (MemoryStream ms = new MemoryStream()) { using (PdfStamper stamper = new PdfStamper(reader, ms)) { } zip.AddEntry(RESULT2, ms.ToArray()); } zip.AddEntry(Utility.ResultFileName(s.ToString() + ".pdf"), stationery); zip.AddEntry(Utility.ResultFileName(ss.ToString() + ".pdf"), sStationery); zip.Save(stream); } }
public byte[] Strip(ZipFile zip, Dictionary<string, Tuple<Cipher, byte[]>> sessionKeys) { IEnumerable<ZipEntry> entriesToDecrypt = zip.Entries.Where(e => !META_NAMES.Contains(e.FileName)); using (var output = new ZipFile(Encoding.UTF8)) { output.UseZip64WhenSaving = Zip64Option.Never; output.CompressionLevel = CompressionLevel.None; using (var s = new MemoryStream()) { zip["mimetype"].Extract(s); output.AddEntry("mimetype", s.ToArray()); } foreach (var file in entriesToDecrypt) { byte[] data; using (var s = new MemoryStream()) { file.Extract(s); data = s.ToArray(); } if (sessionKeys.ContainsKey(file.FileName)) data = Decryptor.Decrypt(data, sessionKeys[file.FileName].Item1, sessionKeys[file.FileName].Item2); var ext = Path.GetExtension(file.FileName); output.CompressionLevel = UncompressibleExts.Contains(ext) ? CompressionLevel.None : CompressionLevel.BestCompression; output.AddEntry(file.FileName, data); } using (var result = new MemoryStream()) { output.Save(result); return result.ToArray(); } } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { MovieLinks1 ml = new MovieLinks1(); MovieHistory mh = new MovieHistory(); List<byte[]> pdf = new List<byte[]>() { Utility.PdfBytes(ml), Utility.PdfBytes(mh) }; string[] names = {ml.ToString(), mh.ToString()}; using (ZipFile zip = new ZipFile()) { using (MemoryStream ms = new MemoryStream()) { // step 1 using (Document document = new Document()) { // step 2 using (PdfCopy copy = new PdfCopy(document, ms)) { // step 3 document.Open(); // step 4 for (int i = 0; i < pdf.Count; ++i) { zip.AddEntry(Utility.ResultFileName(names[i] + ".pdf"), pdf[i]); PdfReader reader = new PdfReader(pdf[i]); // loop over the pages in that document int n = reader.NumberOfPages; for (int page = 0; page < n; ) { copy.AddPage(copy.GetImportedPage(reader, ++page)); } } } } zip.AddEntry(RESULT, ms.ToArray()); } zip.Save(stream); } }
public void OutputZip(HttpResponseBase response, FileHandle dataFile, IEnumerable<FileHandle> photoFiles, IEnumerable<StreamHandle> docmentStreams, string downloadTokenValue, string zipFilename) { using (var zip = new ZipFile()) { zip.UseZip64WhenSaving = Zip64Option.AsNecessary; var pdfList = new List<FileHandle>(); if (dataFile != null) pdfList.Add(dataFile); pdfList.AddRange(photoFiles); PrepareResponse(response, downloadTokenValue, zipFilename); foreach (var pdfHolder in pdfList) { zip.AddEntry(pdfHolder.FileName, pdfHolder.Content); } foreach (var document in docmentStreams) { if (document.ContentStream != null) { zip.AddEntry(document.FileName, document.ContentStream); } } zip.Save(response.OutputStream); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // Use old example to create PDF MovieTemplates mt = new MovieTemplates(); byte[] pdf = Utility.PdfBytes(mt); using (ZipFile zip = new ZipFile()) { using (MemoryStream ms = new MemoryStream()) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, ms); // step 3 document.Open(); // step 4 PdfPTable table = new PdfPTable(2); PdfReader reader = new PdfReader(pdf); int n = reader.NumberOfPages; PdfImportedPage page; for (int i = 1; i <= n; i++) { page = writer.GetImportedPage(reader, i); table.AddCell(Image.GetInstance(page)); } document.Add(table); } zip.AddEntry(RESULT, ms.ToArray()); } zip.AddEntry(Utility.ResultFileName(mt.ToString() + ".pdf"), pdf); zip.Save(stream); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // use one of the previous examples to create a PDF MovieTemplates mt = new MovieTemplates(); // Create a reader byte[] pdf = Utility.PdfBytes(mt); PdfReader reader = new PdfReader(pdf); // loop over all the pages in the original PDF int n = reader.NumberOfPages; using (ZipFile zip = new ZipFile()) { for (int i = 0; i < n; ) { string dest = string.Format(RESULT, ++i); using (MemoryStream ms = new MemoryStream()) { // We'll create as many new PDFs as there are pages // step 1 using (Document document = new Document()) { // step 2 using (PdfCopy copy = new PdfCopy(document, ms)) { // step 3 document.Open(); // step 4 copy.AddPage(copy.GetImportedPage(reader, i)); } } zip.AddEntry(dest, ms.ToArray()); } } zip.AddEntry(Utility.ResultFileName(mt.ToString() + ".pdf"), pdf); zip.Save(stream); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { byte[] pdf = new Superimposing().CreatePdf(); // Create a reader PdfReader reader = new PdfReader(pdf); using (MemoryStream ms = new MemoryStream()) { // step 1 using (Document document = new Document(PageSize.POSTCARD)) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, ms); // step 3 document.Open(); // step 4 PdfContentByte canvas = writer.DirectContent; PdfImportedPage page; for (int i = 1; i <= reader.NumberOfPages; i++) { page = writer.GetImportedPage(reader, i); canvas.AddTemplate(page, 1f, 0, 0, 1, 0, 0); } } zip.AddEntry(RESULT, ms.ToArray()); } zip.AddEntry(SOURCE, pdf); zip.Save(stream); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { HelloWorld h = new HelloWorld(); byte[] pdf = Utility.PdfBytes(h); // Create a reader PdfReader reader = new PdfReader(pdf); string js = File.ReadAllText( Path.Combine(Utility.ResourceJavaScript, RESOURCE) ); using (MemoryStream ms = new MemoryStream()) { using (PdfStamper stamper = new PdfStamper(reader, ms)) { // Add some javascript stamper.JavaScript = js; } zip.AddEntry(RESULT, ms.ToArray()); } zip.AddEntry(RESOURCE, js); zip.AddEntry(Utility.ResultFileName(h.ToString() + ".pdf"), pdf); zip.Save(stream); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { // Use previous examples to create PDF files MovieLinks1 m = new MovieLinks1(); byte[] pdfM = Utility.PdfBytes(m); LinkActions l = new LinkActions(); byte[] pdfL = l.CreatePdf(); // Create readers. PdfReader[] readers = { new PdfReader(pdfL), new PdfReader(pdfM) }; // step 1 //Document document = new Document(); // step 2 using (var ms = new MemoryStream()) { // step 1 using (Document document = new Document()) { using (PdfCopy copy = new PdfCopy(document, ms)) { // step 3 document.Open(); // step 4 int n; // copy the pages of the different PDFs into one document for (int i = 0; i < readers.Length; i++) { readers[i].ConsolidateNamedDestinations(); n = readers[i].NumberOfPages; for (int page = 0; page < n; ) { copy.AddPage(copy.GetImportedPage(readers[i], ++page)); } } // Add named destination copy.AddNamedDestinations( // from the second document SimpleNamedDestination.GetNamedDestination(readers[1], false), // using the page count of the first document as offset readers[0].NumberOfPages ); } zip.AddEntry(RESULT1, ms.ToArray()); } // Create a reader PdfReader reader = new PdfReader(ms.ToArray()); // Convert the remote destinations into local destinations reader.MakeRemoteNamedDestinationsLocal(); using (MemoryStream ms2 = new MemoryStream()) { // Create a new PDF containing the local destinations using (PdfStamper stamper = new PdfStamper(reader, ms2)) { } zip.AddEntry(RESULT2, ms2.ToArray()); } } zip.AddEntry(Utility.ResultFileName(m.ToString() + ".pdf"), pdfM); zip.AddEntry(Utility.ResultFileName(l.ToString() + ".pdf"), pdfL); zip.Save(stream); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { MovieLinks1 ml = new MovieLinks1(); byte[] r1 = Utility.PdfBytes(ml); MovieHistory mh = new MovieHistory(); byte[] r2 = Utility.PdfBytes(mh); using (MemoryStream ms = new MemoryStream()) { // step 1 using (Document document = new Document()) { // step 2 using (PdfCopy copy = new PdfCopy(document, ms)) { // step 3 document.Open(); // step 4 // reader for document 1 PdfReader reader1 = new PdfReader(r1); int n1 = reader1.NumberOfPages; // reader for document 2 PdfReader reader2 = new PdfReader(r2); int n2 = reader2.NumberOfPages; // initializations PdfImportedPage page; PdfCopy.PageStamp stamp; // Loop over the pages of document 1 for (int i = 0; i < n1; ) { page = copy.GetImportedPage(reader1, ++i); stamp = copy.CreatePageStamp(page); // add page numbers ColumnText.ShowTextAligned( stamp.GetUnderContent(), Element.ALIGN_CENTER, new Phrase(string.Format("page {0} of {1}", i, n1 + n2)), 297.5f, 28, 0 ); stamp.AlterContents(); copy.AddPage(page); } // Loop over the pages of document 2 for (int i = 0; i < n2; ) { page = copy.GetImportedPage(reader2, ++i); stamp = copy.CreatePageStamp(page); // add page numbers ColumnText.ShowTextAligned( stamp.GetUnderContent(), Element.ALIGN_CENTER, new Phrase(string.Format("page {0} of {1}", n1 + i, n1 + n2)), 297.5f, 28, 0 ); stamp.AlterContents(); copy.AddPage(page); } } } zip.AddEntry(RESULT, ms.ToArray()); zip.AddEntry(Utility.ResultFileName(ml.ToString() + ".pdf"), r1); zip.AddEntry(Utility.ResultFileName(mh.ToString()+ ".pdf"), r2); } zip.Save(stream); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { PdfXPdfA example = new PdfXPdfA(); zip.AddEntry(RESULT1, example.CreatePdfX()); zip.AddEntry(RESULT2, example.CreatePdfA()); zip.Save(stream); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { PeekABoo peekaboo = new PeekABoo(); zip.AddEntry(RESULT1, peekaboo.CreatePdf(true)); zip.AddEntry(RESULT2, peekaboo.CreatePdf(false)); zip.Save(stream); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { MovieAds movieAds = new MovieAds(); byte[] pdf = movieAds.CreateTemplate(); zip.AddEntry(TEMPLATE, pdf); using (MemoryStream msDoc = new MemoryStream()) { using (Document document = new Document()) { using (PdfSmartCopy copy = new PdfSmartCopy(document, msDoc)) { document.Open(); PdfReader reader; PdfStamper stamper = null; AcroFields form = null; int count = 0; MemoryStream ms = null; using (ms) { foreach (Movie movie in PojoFactory.GetMovies()) { if (count == 0) { ms = new MemoryStream(); reader = new PdfReader(RESOURCE); stamper = new PdfStamper(reader, ms); stamper.FormFlattening = true; form = stamper.AcroFields; } count++; PdfReader ad = new PdfReader( movieAds.FillTemplate(pdf, movie) ); PdfImportedPage page = stamper.GetImportedPage(ad, 1); PushbuttonField bt = form.GetNewPushbuttonFromField( "movie_" + count ); bt.Layout = PushbuttonField.LAYOUT_ICON_ONLY; bt.ProportionalIcon = true; bt.Template = page; form.ReplacePushbuttonField("movie_" + count, bt.Field); if (count == 16) { stamper.Close(); reader = new PdfReader(ms.ToArray()); copy.AddPage(copy.GetImportedPage(reader, 1)); count = 0; } } if (count > 0) { stamper.Close(); reader = new PdfReader(ms.ToArray()); copy.AddPage(copy.GetImportedPage(reader, 1)); } } } } zip.AddEntry(RESULT, msDoc.ToArray()); } zip.AddFile(RESOURCE, ""); zip.Save(stream); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { TextFields example = new TextFields(0); byte[] pdf = example.CreatePdf(); zip.AddEntry(RESULT1, pdf); zip.AddEntry(RESULT2, example.ManipulatePdf(pdf)); zip.Save(stream); } }
// --------------------------------------------------------------------------- public virtual void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { HtmlMovies1 h = new HtmlMovies1(); byte[] pdf = h.CreateHtmlAndPdf(stream); zip.AddEntry(HTML, h.Html.ToString()); zip.AddEntry(PDF, pdf); zip.Save(stream); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { // create first PDF byte[] stationary = CreateStationary(); zip.AddEntry(STATIONERY, stationary); zip.AddEntry(RESULT, CreatePdf(stationary)); zip.Save(stream); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { SpecialId s = new SpecialId(); byte[] pdf = s.CreatePdf(); zip.AddEntry(Utility.ResultFileName(s.ToString() + ".pdf"), pdf); zip.AddEntry(RESULT, new ResizeImage().ManipulatePdf(pdf)); zip.Save(stream); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { ReplaceURL form = new ReplaceURL(); byte[] pdf = form.CreatePdf(); zip.AddEntry(RESULT1, pdf); zip.AddEntry(RESULT2, form.ManipulatePdf(pdf)); zip.Save(stream); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { EmbedFontPostFacto example = new EmbedFontPostFacto(); byte[] pdf = example.CreatePdf(); zip.AddEntry(RESULT1, pdf); zip.AddEntry(RESULT2, example.ManipulatePdf(pdf)); zip.Save(stream); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { CreateOutlineTree example = new CreateOutlineTree(); byte[] pdf = example.CreatePdf(); zip.AddEntry(RESULT, pdf); zip.AddEntry(RESULTXML, example.CreateXml(pdf)); zip.Save(stream); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { CompressImage c = new CompressImage(); zip.AddEntry(RESULT1, c.CreatePdf(false)); zip.AddEntry(RESULT2, c.CreatePdf(true)); zip.AddFile(Path.Combine(Utility.ResourceImage, RESOURCE), ""); zip.Save(stream); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { MovieTemplates m = new MovieTemplates(); byte[] pdf = Utility.PdfBytes(m); zip.AddEntry(RESULT, new NamedActions().ManipulatePdf(pdf)); zip.AddEntry(Utility.ResultFileName(m.ToString() + ".pdf"), pdf); zip.Save(stream); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { MetadataPdf metadata = new MetadataPdf(); byte[] pdf = metadata.CreatePdf(); zip.AddEntry(RESULT1, pdf); zip.AddEntry(RESULT2, metadata.ManipulatePdf(pdf)); zip.Save(stream); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { ChoiceFields fields = new ChoiceFields(0); byte[] pdf = fields.CreatePdf(); zip.AddEntry(RESULT1, pdf); zip.AddEntry(RESULT2, fields.ManipulatePdf(pdf)); zip.Save(stream); } }
public void Save() { //archive.UpdateEntry(name, Document.ToString()); //using (var stream = entry.Open()) //{ // stream.Seek(0, SeekOrigin.End); // using (var sw = new StreamWriter(stream)) // { // sw.Write(Document.ToString()); // sw.Flush(); // } //} var path = AppDomain.CurrentDomain.BaseDirectory + "temp.xml"; Document.Save(path); archive.RemoveEntry(entry); archive.AddEntry(name, new FileStream(path, FileMode.Open)); archive.Save(); //using (var s = new MemoryStream()) //{ // using (var sw = new StreamWriter(s)) // { // var xml = Document.ToString(); // sw.WriteLine("123"); // sw.Flush(); // archive.AddEntry("test.xml", s); // archive.Save(); // } // //Document.Save(s); //} }
/// <summary> /// Append the zip data to the file-entry specified. /// </summary> /// <param name="path"></param> /// <param name="entry"></param> /// <param name="data"></param> /// <returns></returns> public static bool ZipCreateAppendData(string path, string entry, string data) { try { if (File.Exists(path)) { using (var zip = ZipFile.Read(path)) { zip.AddEntry(entry, data); zip.Save(); } } else { using (var zip = new ZipFile(path)) { zip.AddEntry(entry, data); zip.Save(); } } } catch (Exception err) { Log.Error(err); return(false); } return(true); }
/// <summary> /// compress the files /// </summary> /// <param name="FolderToZip"></param> /// <param name="s"></param> /// <param name="ParentFolderName"></param> private static bool ZipFileDictory(string FolderToZip, string ParentFolderName, Ionic.Zip.ZipFile zip) { bool res = true; string[] folders, filenames; ZipEntry entry = null; FileStream fs = null; try { //create current folder using (Ionic.Zip.ZipFile izip = new Ionic.Zip.ZipFile(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip)), Encoding.UTF8)) { //first compress the file, then the folder filenames = Directory.GetFiles(FolderToZip); foreach (string file in filenames) { if (File.Exists(file)) { using (FileStream innerfs = new FileStream(file, FileMode.Open, FileAccess.Read)) { byte[] buffer = new byte[innerfs.Length]; innerfs.Read(buffer, 0, buffer.Length); string fileName = file.Substring(file.LastIndexOf("\\") + 1); izip.AddEntry(fileName, buffer); } } } } } catch { res = false; } finally { if (fs != null) { fs.Close(); fs = null; } if (entry != null) { entry = null; } GC.Collect(); GC.Collect(1); } folders = Directory.GetDirectories(FolderToZip); foreach (string folder in folders) { if (!ZipFileDictory(folder, Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip)), zip)) { return(false); } } return(res); }
public void CreateFile(string filename) { MemoryStream memory = new MemoryStream(); var bytes = ReadBytes(filename); memory.Write(bytes, 0, bytes.Length); using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(path)) { ZipEntry e = zip.AddEntry(filename, memory); // zip.AddFile(filename); zip.Save(); } }
/// <summary> /// 压缩zip /// </summary> /// <param name="fileToZips">文件路径集合</param> /// <param name="zipedFile">想要压成zip的文件名</param> public static void Zip(string[] fileToZips, string zipedFile) { using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipedFile, Encoding.Default)) { foreach (string fileToZip in fileToZips) { using (FileStream fs = new FileStream(fileToZip, FileMode.Open, FileAccess.ReadWrite)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); string fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\") + 1); zip.AddEntry(fileName, buffer); } } zip.Save(); } }
public static void Compress(string zipfile, Dictionary <string, string> entrys, Encoding encoding = default(Encoding)) { if (encoding == default(Encoding)) { encoding = Encoding.Default; } using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(encoding)) { foreach (var key in entrys.Keys) { if (File.Exists(entrys[key])) { zip.AddEntry(key, File.OpenRead(entrys[key])); } } zip.Save(zipfile); } }
private byte[] IncludeZip(string file, string fileName) { byte[] ziplenecekData = Encoding.UTF8.GetBytes(file); MemoryStream zipStream = new MemoryStream(); using (ZipFile zip = new Ionic.Zip.ZipFile()) { ZipEntry zipEleman = zip.AddEntry(fileName + ".txt", ziplenecekData); zip.Save(zipStream); } zipStream.Seek(0, SeekOrigin.Begin); zipStream.Flush(); zipStream.Position = 0; return(zipStream.ToArray()); }
/** Compressess given source string into a zip file formatted as base64 */ public static string Compress(string source) { #if ZIP_NONE return(System.Convert.ToBase64String(Encoding.UTF8.GetBytes(source))); #endif #if ZIP_IONIC using (var zip = new Ionic.Zip.ZipFile()) { // compressed data, then converts back to a string again zip.AddEntry("x", source); var zipOutput = new MemoryStream(); zip.Save(zipOutput); // Base 64 encoding (so that I can embed it in an XML file. return(System.Convert.ToBase64String(zipOutput.ToArray())); } #endif #if ZIP_SHARP using (MemoryStream fsOut = new MemoryStream()) { using (var zipStream = new ZipOutputStream(fsOut)) { zipStream.SetLevel(3); var newEntry = new ZipEntry("X"); zipStream.PutNextEntry(newEntry); var sourceBytes = Encoding.UTF8.GetBytes(source); Util.CopyStream(new MemoryStream(sourceBytes), zipStream); zipStream.CloseEntry(); zipStream.IsStreamOwner = false; zipStream.Close(); } // Base 64 encoding (so that I can embed it in an XML file. return(Convert.ToBase64String(fsOut.ToArray())); } #endif }
/// <summary> /// 压缩文件 /// </summary> /// <param name="entrys">新文件名,支持目录 => 原始文件名</param> /// <param name="encoding">编码</param> /// <returns></returns> public static Stream CompressOutStream(Dictionary <string, string> entrys, Encoding encoding = default(Encoding)) { if (encoding == default(Encoding)) { encoding = Encoding.Default; } MemoryStream stream = new MemoryStream(); using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(encoding)) { foreach (var key in entrys.Keys) { if (File.Exists(entrys[key])) { zip.AddEntry(key, File.OpenRead(entrys[key])); } } zip.Save(stream); stream.Position = 0; } return(stream); }
private static ZipOutputStream CreateNewStream(ArrayList htmlFile, string outPath, out long HTMLstreamlenght) { ZipOutputStream oZipStream = new ZipOutputStream(File.Create(outPath), false);// create zip stream // Compression level of zip file. oZipStream.CompressionLevel = 0; const int BufferSize = 4096; byte[] obuffer = new byte[BufferSize]; HTMLstreamlenght = 0; //FileStream htmlstream = null; ZipEntry oHtmlEntry = new ZipEntry(); using (Ionic.Zip.ZipFile htmlZip = new Ionic.Zip.ZipFile()) { foreach (string htmlFil in htmlFile.ToArray()) // for each file, generate a zip entry { oHtmlEntry = htmlZip.AddEntry(Path.GetFileName(htmlFil.ToString()), htmlFil); oZipStream.PutNextEntry(oHtmlEntry.FileName); using (FileStream htmlstream = File.OpenRead(htmlFil)) { int read; while ((read = htmlstream.Read(obuffer, 0, obuffer.Length)) > 0) { oZipStream.Write(obuffer, 0, read); } } } htmlZip.Dispose(); } HTMLstreamlenght = oZipStream.Position; return(oZipStream); }
/// <summary> /// This method generate the package as per the <c>PackageSize</c> declare. /// Currently <c>PackageSize</c> is 2 GB. /// </summary> /// <param name="inputFolderPath">Input folder Path.</param> /// <param name="outputFolderandFile">Output folder Path.</param> static void SplitZipFolder(string inputFolderPath, string outputFolderandFile, string threadId) { #region otherApproach #endregion int cnt = 1; m_packageSize = m_packageSize * 20; ArrayList htmlFile = new ArrayList(); ArrayList ar = GenerateFileList(inputFolderPath, out htmlFile); // generate file list // Output Zip file name. string outPath = Path.Combine(outputFolderandFile, threadId + "-" + cnt + ".zip"); long HTMLstreamlenght = 0; using (ZipOutputStream oZipStream = CreateNewStream(htmlFile, outPath, out HTMLstreamlenght)) { // Initialize the zip entry object. ZipEntry oZipEntry = new ZipEntry(); // numbers of files in file list. var counter = ar.Count; try { using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { Array.Sort(ar.ToArray()); // Sort the file list array. foreach (string Fil in ar.ToArray()) // for each file, generate a zip entry { if (!Fil.EndsWith(@"/")) // if a file ends with '/' its a directory { if (!zip.ContainsEntry(Path.GetFileName(Fil.ToString()))) { oZipEntry = zip.AddEntry("Attachments/" + Path.GetFileName(Fil.ToString()), Fil); counter--; try { if (counter >= 0) { long streamlenght = HTMLstreamlenght; const int BufferSize = 4096; byte[] obuffer = new byte[BufferSize]; if (oZipStream.Position + streamlenght < m_packageSize) { using (FileStream ostream = File.OpenRead(Fil)) { //ostream = File.OpenRead(Fil); using (ZipOutputStream tempZStream = new ZipOutputStream(File.Create(Directory.GetCurrentDirectory() + "\\test.zip"), false)) { tempZStream.PutNextEntry(oZipEntry.FileName); int tempread; while ((tempread = ostream.Read(obuffer, 0, obuffer.Length)) > 0) { tempZStream.Write(obuffer, 0, tempread); } streamlenght = tempZStream.Position; tempZStream.Dispose(); tempZStream.Flush(); tempZStream.Close(); // close the zip stream. // ostream.Dispose(); } File.Delete(Directory.GetCurrentDirectory() + "\\test.zip"); } } if (oZipStream.Position + streamlenght > m_packageSize) { zip.RemoveEntry(oZipEntry); zip.Dispose(); oZipStream.Dispose(); oZipStream.Flush(); oZipStream.Close(); // close the zip stream. cnt = cnt + 1; outPath = Path.Combine(outputFolderandFile, threadId + "-" + cnt.ToString() + ".zip"); // create new output zip file when package size. using (ZipOutputStream oZipStream2 = CreateNewStream(htmlFile, outPath, out HTMLstreamlenght)) { oZipStream2.PutNextEntry(oZipEntry.FileName); using (FileStream ostream = File.OpenRead(Fil)) { int read; while ((read = ostream.Read(obuffer, 0, obuffer.Length)) > 0) { oZipStream2.Write(obuffer, 0, read); } } } } else { oZipStream.PutNextEntry(oZipEntry.FileName); using (FileStream ostream = File.OpenRead(Fil)) { int read; while ((read = ostream.Read(obuffer, 0, obuffer.Length)) > 0) { oZipStream.Write(obuffer, 0, read); } } } } else { Console.WriteLine("No more file existed in directory"); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); zip.RemoveEntry(oZipEntry.FileName); } } else { Console.WriteLine("File Existed {0} in Zip {1}", Path.GetFullPath(Fil.ToString()), outPath); } } } zip.Dispose(); } oZipStream.Dispose(); oZipStream.Flush(); oZipStream.Close();// close stream } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { oZipStream.Dispose(); oZipStream.Flush(); oZipStream.Close();// close stream Console.WriteLine("Remain Files{0}", counter); } } }
public IZipEntry AddFile(string path, Stream stream) { return(new MZipEntry(zip.AddEntry(path, stream))); }
void Publish() { string webplayer = PlayerPrefs.GetString("Course_Export"); string tempdir = System.IO.Path.GetTempPath() + System.IO.Path.GetRandomFileName(); System.IO.Directory.CreateDirectory(tempdir); CopyFilesRecursively(new System.IO.DirectoryInfo(webplayer), new System.IO.DirectoryInfo(tempdir)); string zipfile = EditorUtility.SaveFilePanel("Choose Output File", webplayer, PlayerPrefs.GetString("Course_Title"), "zip"); if (zipfile != "") { if (File.Exists(zipfile)) { File.Delete(zipfile); } Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipfile); zip.AddDirectory(tempdir); if (PlayerPrefs.GetInt("SCORM_Version") < 3) { zip.AddItem(Application.dataPath + "/ADL SCORM/Plugins/2004"); string manifest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<!-- exported by Unity-SCORM Integration Toolkit Version 1.4 Beta-->" + "<manifest xmlns=\"http://www.imsglobal.org/xsd/imscp_v1p1\" xmlns:imsmd=\"http://www.imsglobal.org/xsd/imsmd_v1p2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:adlcp=\"http://www.adlnet.org/xsd/adlcp_v1p3\" xmlns:imsss=\"http://www.imsglobal.org/xsd/imsss\" xmlns:adlseq=\"http://www.adlnet.org/xsd/adlseq_v1p3\" xmlns:adlnav=\"http://www.adlnet.org/xsd/adlnav_v1p3\" identifier=\"MANIFEST-AECEF15E-06B8-1FAB-5289-73A0B058E2DD\" xsi:schemaLocation=\"http://www.imsglobal.org/xsd/imscp_v1p1 imscp_v1p1.xsd http://www.imsglobal.org/xsd/imsmd_v1p2 imsmd_v1p2p2.xsd http://www.adlnet.org/xsd/adlcp_v1p3 adlcp_v1p3.xsd http://www.imsglobal.org/xsd/imsss imsss_v1p0.xsd http://www.adlnet.org/xsd/adlseq_v1p3 adlseq_v1p3.xsd http://www.adlnet.org/xsd/adlnav_v1p3 adlnav_v1p3.xsd\" version=\"1.3\">" + " <metadata>" + " <schema>ADL SCORM</schema>" + ((PlayerPrefs.GetInt("SCORM_Version") == 0)?" <schemaversion>2004 4th Edition</schemaversion>":"") + ((PlayerPrefs.GetInt("SCORM_Version") == 1)?" <schemaversion>2004 3rd Edition</schemaversion>":"") + ((PlayerPrefs.GetInt("SCORM_Version") == 2)?" <schemaversion>2004 CAM 1.3</schemaversion>":"") + " </metadata>" + " <organizations default=\"ORG-8770D9D9-AD66-06BB-9A3D-E87784C697FF\">" + " <organization identifier=\"ORG-8770D9D9-AD66-06BB-9A3D-E87784C697FF\">" + " <title>" + PlayerPrefs.GetString("Course_Title") + "</title>" + " <item identifier=\"ITEM-79701DB3-F0AD-9426-8C43-819F3CB0EE6E\" identifierref=\"RES-4F17946A-9286-D5F0-7B6A-04E980C04F46\" parameters=\"" + GetParameterString() + "\">" + " <title>"+ PlayerPrefs.GetString("SCO_Title") + "</title>" + " <adlcp:dataFromLMS>"+ PlayerPrefs.GetString("Data_From_Lms") + "</adlcp:dataFromLMS>" + " <adlcp:completionThreshold completedByMeasure = \""+ (System.Convert.ToBoolean(PlayerPrefs.GetInt("completedByMeasure"))).ToString().ToLower() + "\" minProgressMeasure= \"" + PlayerPrefs.GetFloat("minProgressMeasure") + "\" />"; if (PlayerPrefs.GetInt("satisfiedByMeasure") == 1) { manifest += " <imsss:sequencing>"+ " <imsss:objectives>"+ " <imsss:primaryObjective objectiveID = \"PRIMARYOBJ\""+ " satisfiedByMeasure = \""+ (System.Convert.ToBoolean(PlayerPrefs.GetInt("satisfiedByMeasure"))).ToString().ToLower() + "\">" + " <imsss:minNormalizedMeasure>"+ PlayerPrefs.GetFloat("minNormalizedMeasure") + "</imsss:minNormalizedMeasure>" + " </imsss:primaryObjective>"+ " </imsss:objectives>"+ " </imsss:sequencing>"; } manifest += " </item>" + " </organization>" + " </organizations>" + " <resources>" + " <resource identifier=\"RES-4F17946A-9286-D5F0-7B6A-04E980C04F46\" type=\"webcontent\" href=\"WebPlayer/WebPlayer.html\" adlcp:scormType=\"sco\">" + " <file href=\"WebPlayer/WebPlayer.html\" />" + " <file href=\"WebPlayer/scripts/scorm.js\" />" + " <file href=\"WebPlayer/scripts/ScormSimulator.js\" />"+ " <file href=\"WebPlayer/UnityObject.js\" />"+ " <file href=\"WebPlayer/Webplayer.unity3d\" />"+ " <file href=\"WebPlayer/images/scorm_progres_bar.png\" />"+ " <file href=\"WebPlayer/images/thumbnail.png\" />"+ " </resource>" + " </resources>" + "</manifest>"; zip.AddEntry("imsmanifest.xml", ".", System.Text.ASCIIEncoding.ASCII.GetBytes(manifest)); } else { zip.AddItem(Application.dataPath + "/ADL SCORM/Plugins/1.2"); string manifest = "<?xml version=\"1.0\"?>" + "<!-- exported by Unity-SCORM Integration Toolkit Version 1.4 Beta-->" + "<manifest identifier=\"SingleCourseManifest\" version=\"1.1\"" + " xmlns=\"http://www.imsproject.org/xsd/imscp_rootv1p1p2\"" + " xmlns:adlcp=\"http://www.adlnet.org/xsd/adlcp_rootv1p2\"" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + " xsi:schemaLocation=\"http://www.imsproject.org/xsd/imscp_rootv1p1p2 imscp_rootv1p1p2.xsd" + " http://www.imsglobal.org/xsd/imsmd_rootv1p2p1 imsmd_rootv1p2p1.xsd" + " http://www.adlnet.org/xsd/adlcp_rootv1p2 adlcp_rootv1p2.xsd\">" + " <organizations default=\"B0\">" + " <organization identifier=\"B0\">" + " <title>" + PlayerPrefs.GetString("Course_Title") + "</title>" + " <item identifier=\"IS12\" identifierref=\"RS12\" parameters=\""+ GetParameterString() + "\">" + " <title>"+ PlayerPrefs.GetString("SCO_Title") + "</title>" + " <adlcp:dataFromLMS>"+ PlayerPrefs.GetString("Data_From_Lms") + "</adlcp:dataFromLMS>" + " <adlcp:masteryscore>"+ PlayerPrefs.GetFloat("masteryscore") + "</adlcp:masteryscore>" + " </item>"+ " </organization>"+ " </organizations>"+ " <resources>"+ " <resource identifier=\"RS12\" type=\"webcontent\""+ " adlcp:scormtype=\"sco\" href=\"WebPlayer/WebPlayer.html\">"+ " </resource>"+ " </resources>"+ " </manifest>"; zip.AddEntry("imsmanifest.xml", ".", System.Text.ASCIIEncoding.ASCII.GetBytes(manifest)); } zip.Save(); } }
/// <summary> /// Not for external use. Assumes 'state' is a BatchResizeSettings instance, and stores it in a class member. /// Next, it completes (or fails at) the job. Throws exceptions only if (a) state is not a BatchResizeSettings instance, or (b) an exception is thrown by and handler of the JobEvent (Failed) event. /// </summary> /// <param name="state"></param> protected internal void Work(object state) { s = (BatchResizeSettings)state; try { //Time the job. jobTimer = new Stopwatch(); jobTimer.Start(); //1) Eliminate duplicate target filenames, sanitize, and add appropriate extensions, then mark all items as immutable s.FixDuplicateFilenames(); s.AppendFinalExtensions(); s.MarkItemsImmutable(); //2) Build dictionary based on target filenames. items = BuildDict(s.files); //3) Verify destination folder exists, otherwise create it. (early detection of security failures) CreateDestinationFolder(); //4) Open zip file (writes to a temporary location, then moves the file when it is done) using (Ionic.Zip.ZipFile z = new Ionic.Zip.ZipFile(s.destinationFile)) { //Compress for speed. z.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed; //Fire events instead of throwing exceptions z.ZipErrorAction = ZipErrorAction.InvokeErrorEvent; z.ZipError += new EventHandler <ZipErrorEventArgs>(z_ZipError); z.SaveProgress += new EventHandler <SaveProgressEventArgs>(z_SaveProgress); //5) Create a list to store item resize/compression results results = new List <ItemResult>(); //6) Queue the files that will be included in the archive, specifying a callback for items foreach (BatchResizeItem i in s.files) { try{ ZipEntry ze = z.AddEntry(i.TargetFilename, new WriteDelegate(WriteItemCallback)); //Don't try to compress files we have already resized, it won't help, just slow things down and possibly use more space. if (wouldResize(i)) { ze.CompressionMethod = CompressionMethod.None; } else { //Set the times //ze.SetEntryTimes(System.IO.File.GetLastWriteTimeUtc(i.PhysicalPath), // System.IO.File.GetLastAccessTimeUtc(i.PhysicalPath), // System.IO.File.GetCreationTimeUtc(i.PhysicalPath)); //Never mind, not desired behavior. } }catch (Exception ex) { ItemFailed(i, ex); } } //7) Begin processing the queue. //As each file is written to the archive, a callback is invoked which actually provides the resized stream. z.Save(); } //8) Close zip file jobTimer.Stop(); //9) Fire the event that says "We're done!" JobCompleted(s); } catch (Exception ex) { //Admit we failed to whoever is listening. JobFailed(s, ex); } }
/// <summary> /// zip when has special file /// </summary> /// <param name="fileToZips"></param> /// <param name="zipedFile"></param> /// <param name="basePath"></param> public static void ZipAdvanced(string[] fileToZips, string zipedFile, string basePath) { using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipedFile, Encoding.GetEncoding(932))) { zip.UseZip64WhenSaving = Ionic.Zip.Zip64Option.Always; zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed; zip.BufferSize = 65536 * 8; // Set the buffersize to 512k for better efficiency with large files foreach (string fileToZip in fileToZips) { if (LongPath.IsFileExists(fileToZip)) { FileStream fs = LongPath.OpenForOnlyRead(fileToZip); zip.AddEntry(fileToZip.Substring(basePath.Length), fs); continue; } else //文件夹 { if (Directory.Exists(fileToZip)) { foreach (var e in Directory.EnumerateFiles(fileToZip, "*", SearchOption.AllDirectories)) { try { //判断文件名是否以空格结尾 bool spaceEnd = false; string name = e.Substring(e.LastIndexOf('\\') + 1); if (name.TrimEnd().Length < name.Length) { spaceEnd = true; } if (!spaceEnd && File.Exists(e)) { zip.AddFile(e, e.Substring(basePath.Length, e.LastIndexOf('\\') - basePath.Length)); } else { string entryName = e.Substring(basePath.Length); /* * 末尾添加全角空格,(ps:如果同一目录下有个 文件a 又有一个文件 a空格 则解压时会同名冲突,故添加全角空格以区分 */ if (spaceEnd) { entryName += " "; } FileStream fs = LongPath.OpenForOnlyRead(e); zip.AddEntry(entryName, fs); } } catch (Exception ex) { logger.Error("path:" + e + Environment.NewLine + ex.Message); } } } else { foreach (String path in FilesystemHelper.EnumFilesYield(fileToZip)) { try { FileStream fs = LongPath.OpenForOnlyRead(path); zip.AddEntry(path.Substring(basePath.Length), fs); } catch (Exception ex) { logger.Error("path:" + path + Environment.NewLine + ex.Message); } } } } } zip.Save(); } }
/// <summary> /// Publish this SCORM package to a conformant zip file. /// </summary> void Publish() { string timeLimitAction = ""; switch (PlayerPrefs.GetInt("Time_Limit_Action")) { case 0: timeLimitAction = ""; break; case 1: timeLimitAction = "exit,message"; break; case 2: timeLimitAction = "exit,no message"; break; case 3: timeLimitAction = "continue,message"; break; case 4: timeLimitAction = "continue,no message"; break; } string timeLimit = SecondsToTimeInterval(ParseFloat(PlayerPrefs.GetString("Time_Limit_Secs"))); string webplayer = PlayerPrefs.GetString("Course_Export"); string tempdir = System.IO.Path.GetTempPath() + System.IO.Path.GetRandomFileName(); System.IO.Directory.CreateDirectory(tempdir); CopyFilesRecursively(new System.IO.DirectoryInfo(webplayer), new System.IO.DirectoryInfo(tempdir)); string zipfile = EditorUtility.SaveFilePanel("Choose Output File", webplayer, PlayerPrefs.GetString("Course_Title"), "zip"); if (zipfile != "") { if (File.Exists(zipfile)) { File.Delete(zipfile); } Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipfile); zip.AddDirectory(tempdir); zip.AddItem(Application.dataPath + "/SCORM/Plugins/2004"); string manifest = "<?xml version=\"1.0\" standalone=\"no\" ?>\n" + "<manifest identifier=\"" + PlayerPrefs.GetString("Manifest_Identifier") + "\" version=\"1\"\n" + "\t\txmlns = \"http://www.imsglobal.org/xsd/imscp_v1p1\"\n" + "\t\txmlns:adlcp = \"http://www.adlnet.org/xsd/adlcp_v1p3\"\n" + "\t\txmlns:adlseq = \"http://www.adlnet.org/xsd/adlseq_v1p3\"\n" + "\t\txmlns:adlnav = \"http://www.adlnet.org/xsd/adlnav_v1p3\"\n" + "\t\txmlns:imsss = \"http://www.imsglobal.org/xsd/imsss\"\n" + "\t\txmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n" + "\t\txmlns:lom=\"http://ltsc.ieee.org/xsd/LOM\"\n" + "\t\txsi:schemaLocation = \"http://www.imsglobal.org/xsd/imscp_v1p1 imscp_v1p1.xsd\n" + "\t\t\thttp://www.adlnet.org/xsd/adlcp_v1p3 adlcp_v1p3.xsd\n" + "\t\t\thttp://www.adlnet.org/xsd/adlseq_v1p3 adlseq_v1p3.xsd\n" + "\t\t\thttp://www.adlnet.org/xsd/adlnav_v1p3 adlnav_v1p3.xsd\n" + "\t\t\thttp://www.imsglobal.org/xsd/imsss imsss_v1p0.xsd\n" + "\t\t\thttp://ltsc.ieee.org/xsd/LOM lom.xsd\" >\n" + "<metadata>\n" + "\t<schema>ADL SCORM</schema>\n" + "\t<schemaversion>2004 4th Edition</schemaversion>\n" + "<lom:lom>\n" + "\t<lom:general>\n" + "\t\t<lom:description>\n" + "\t\t\t<lom:string language=\"en-US\">" + PlayerPrefs.GetString("Course_Description") + "</lom:string>\n" + "\t\t</lom:description>\n" + "\t</lom:general>\n" + "\t</lom:lom>\n" + "</metadata>\n" + "<organizations default=\"B0\">\n" + "\t<organization identifier=\"B0\" adlseq:objectivesGlobalToSystem=\"false\">\n" + "\t\t<title>" + PlayerPrefs.GetString("Course_Title") + "</title>\n" + "\t\t<item identifier=\"i1\" identifierref=\"r1\" isvisible=\"true\">\n" + "\t\t\t<title>" + PlayerPrefs.GetString("SCO_Title") + "</title>\n" + "\t\t\t<adlcp:timeLimitAction>" + timeLimitAction + "</adlcp:timeLimitAction>\n" + "\t\t\t<adlcp:dataFromLMS>" + PlayerPrefs.GetString("Data_From_Lms") + "</adlcp:dataFromLMS> \n" + "\t\t\t<adlcp:completionThreshold completedByMeasure = \"" + (System.Convert.ToBoolean(PlayerPrefs.GetInt("completedByMeasure"))).ToString().ToLower() + "\" minProgressMeasure= \"" + PlayerPrefs.GetFloat("minProgressMeasure") + "\" />\n" + "\t\t\t<imsss:sequencing>\n" + "\t\t\t<imsss:limitConditions attemptAbsoluteDurationLimit=\"" + timeLimit + "\"/>\n" + "\t\t\t</imsss:sequencing>\n" + "\t\t</item>\n" + "\t</organization>\n" + "</organizations>\n" + "<resources>\n" + "\t<resource identifier=\"r1\" type=\"webcontent\" adlcp:scormType=\"sco\" href=\"" + PlayerPrefs.GetString("Course_Export_Name") + ".html\">\n" + "\t\t<file href=\"" + PlayerPrefs.GetString("Course_Export_Name") + ".html\" />\n" + "\t\t<file href=\"scripts/scorm.js\" />\n" + "\t\t<file href=\"scripts/ScormSimulator.js\" />\n" + "\t\t<file href=\"" + PlayerPrefs.GetString("Course_Export_Name") + ".unity3d\" />\n" + "\t</resource>\n" + "</resources>\n" + "</manifest>"; zip.AddEntry("imsmanifest.xml", ".", System.Text.ASCIIEncoding.ASCII.GetBytes(manifest)); zip.Save(); EditorUtility.DisplayDialog("SCORM Package Published", "The SCORM Package has been published to " + zipfile, "OK"); } }
// --------------------------------------------------------------------------- public override void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { HtmlMovies2 movies = new HtmlMovies2(); // create a StyleSheet StyleSheet styles = new StyleSheet(); styles.LoadTagStyle("ul", "indent", "10"); styles.LoadTagStyle("li", "leading", "14"); styles.LoadStyle("country", "i", ""); styles.LoadStyle("country", "color", "#008080"); styles.LoadStyle("director", "b", ""); styles.LoadStyle("director", "color", "midnightblue"); movies.SetStyles(styles); // create extra properties Dictionary<String,Object> map = new Dictionary<String, Object>(); map.Add(HTMLWorker.FONT_PROVIDER, new MyFontFactory()); map.Add(HTMLWorker.IMG_PROVIDER, new MyImageFactory()); movies.SetProviders(map); // creates HTML and PDF (reusing a method from the super class) byte[] pdf = movies.CreateHtmlAndPdf(stream); zip.AddEntry(HTML, movies.Html.ToString()); zip.AddEntry(RESULT1, pdf); zip.AddEntry(RESULT2, movies.CreatePdf()); // add the images so the static html file works foreach (Movie movie in PojoFactory.GetMovies()) { zip.AddFile( Path.Combine( Utility.ResourcePosters, string.Format("{0}.jpg", movie.Imdb) ), "" ); } zip.Save(stream); } }