AddDirectoryByName() public method

Creates a directory in the zip archive.

Use this when you want to create a directory in the archive but there is no corresponding filesystem representation for that directory.

You will probably not need to do this in your code. One of the only times you will want to do this is if you want an empty directory in the zip archive. The reason: if you add a file to a zip archive that is stored within a multi-level directory, all of the directory tree is implicitly created in the zip archive.

public AddDirectoryByName ( string directoryNameInArchive ) : ZipEntry
directoryNameInArchive string /// The name of the directory to create in the archive. ///
return ZipEntry
Beispiel #1
0
        /// <summary>
        /// 压缩zip
        /// </summary>
        /// <param name="fileToZips">文件路径集合</param>
        /// <param name="zipedFile">想要压成zip的文件名</param>
        public static void ZipOld(string[] fileToZips, string zipedFile)
        {
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipedFile, Encoding.UTF8))
            {
                List <string> pathlist = new List <string>();
                foreach (string fileToZip in fileToZips)
                {
                    if (System.IO.File.Exists(fileToZip))
                    {
                        using (FileStream fs = new FileStream(fileToZip, FileMode.Open, FileAccess.Read))
                        {
                            byte[] buffer = new byte[fs.Length];
                            fs.Read(buffer, 0, buffer.Length);
                            string fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\") + 1);
                            string filePath = fileToZip.Substring(0, fileToZip.LastIndexOf("\\"));

                            if (!pathlist.Exists(x => x.Equals(filePath)))
                            {
                                pathlist.Add(filePath);
                                zip.AddDirectoryByName(filePath);
                            }
                            zip.AddFile(fileToZip, filePath);
                        }
                    }
                    if (System.IO.Directory.Exists(fileToZip))
                    {
                        string filePath = fileToZip.Substring(fileToZip.IndexOf("\\") + 1);
                        zip.AddDirectoryByName(filePath);
                        zip.AddDirectory(fileToZip, filePath);
                        //ZipFileDictory(fileToZip, "", zip);
                    }
                }
                zip.Save();
            }
        }
        public static void GenerateEPUB(string inputFile, string outputFile, ConversionOptions options)
        {
            ZipFile file = new ZipFile(outputFile);

            //generate mimetype
            using (Stream mime = new MemoryStream())
            {
                byte[] mimeBytes = System.Text.Encoding.ASCII.GetBytes(_mimetype);
                mime.Write(mimeBytes, 0, mimeBytes.Length);
                file.AddEntry("mimetype", mime);
            }

            //generate META-INF
            file.AddDirectoryByName("META-INF");
            {
                //container.xml
                using (Stream container = new MemoryStream())
                {
                    byte[] containerBytes = System.Text.Encoding.ASCII.GetBytes(Crabwise.PDFtoEPUB.Properties.Resources.container);
                    container.Write(containerBytes, 0, containerBytes.Length);
                    file.AddEntry("META-INF\\container.xml", container);
                }
            }
            //generate OEBPS
            file.AddDirectoryByName("OEBPS");
            {
                //images
                file.AddDirectoryByName("OEBPS\\IMAGES");
                {
                    //add each image to the directory
                }

                //xhtml chapters

                //page-template.xpgt
                byte[] pagetemplateBytes = System.Text.Encoding.ASCII.GetBytes(Properties.Resources.page_template);
                file.AddEntry("OEBPS\\page-template.xpgt", pagetemplateBytes);

                //stylesheet.css
                byte[] stylesheetBytes = System.Text.Encoding.ASCII.GetBytes(Properties.Resources.stylesheet);
                file.AddEntry("OEBPS\\stylesheet.css", stylesheetBytes);

                //title_page.xhtml
                file.AddEntry("OEBPS\\title_page.xhtml", TitlePageGenerator.GetTitlePage(options));

                //Content.opf
                file.AddEntry("OEBPS\\content.opf", ContentFileGenerator.GetContentFile(options));

                //toc.ncx
                file.AddEntry("OEBPS\\toc.ncx", TOCFileGenerator.GetTOCFile(options));

            }
        }
        public FileResult batchDownload(string runids)
        {
            List <string> filepaths = new List <string>();

            foreach (string runid in runids.Split(","))
            {
                filepaths.Add(_context.getRawPath(Convert.ToInt32(runid.Split("-")[1])).Replace("json", "txt"));
            }

            //filepaths.Add(@"C:\Users\griff\Downloads\RUN_20191223_164427_CP53.json");

            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
            {
                zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                zip.AddDirectoryByName("runs");
                foreach (string filepath in filepaths)
                {
                    zip.AddFile(filepath, "runs");
                }
                string zipName = String.Format("RawArchive_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    zip.Save(memoryStream);
                    return(File(memoryStream.ToArray(), "application/zip", zipName));
                }
            }
        }
        public FileResult GetPages()
        {
            if (Request.Url != null)
            {
                var zip = new ZipFile();
                zip.AddDirectoryByName("Content");
                zip.AddDirectory(Server.MapPath("~/Content/"), "Content");
                var paths = DtoHelper.GetPaths();
                foreach (var path in paths)
                {
                    var url = Url.Action(path.Action, path.Controller, null, Request.Url.Scheme);
                    if (url != null)
                    {
                        var request = WebRequest.Create(string.Concat(url, Constants.Resources.DownloadParameter));
                        request.Credentials = CredentialCache.DefaultCredentials;
                        var response = (HttpWebResponse)request.GetResponse();
                        var dataStream = response.GetResponseStream();
                        {
                            if (dataStream != null)
                            {
                                zip.AddEntry(path.FileName, dataStream);
                            }
                        }
                    }
                }
                var stream = new MemoryStream();
                zip.Save(stream);
                stream.Position = 0;
                return new FileStreamResult(stream, "application/zip") { FileDownloadName = Constants.Resources.DownloadName };

            }
            return null;
        }
Beispiel #5
0
        public override void Build()
        {
            UpdateNlib();
            string outp = BuildPath + "main.js";

            File.Delete(outp);
            foreach (var library in Libraries)
            {
                string text = library.GetCode();
                File.AppendAllText(outp, "\n" + text, ProgramData.Encoding);
            }
            foreach (var file in Directory.GetFiles(ScriptsPath))
            {
                string text = File.ReadAllText(file, ProgramData.Encoding);
                File.AppendAllText(outp, "\n" + text, ProgramData.Encoding);
            }
            if (Compress)
            {
                JavaScriptCompressor compressor = new JavaScriptCompressor();
                File.WriteAllText(outp, compressor.Compress(File.ReadAllText(outp, ProgramData.Encoding)), ProgramData.Encoding);
            }

            foreach (var file in OutFiles)
            {
                File.Copy(file, BuildPath + System.IO.Path.GetFileName(file), true);
                File.Copy(file, OutPath + System.IO.Path.GetFileName(file), true);
            }

            using (var zip = new Ionic.Zip.ZipFile())
            {
                zip.AddDirectoryByName("images");
                zip.AddDirectory(ResPath, "images");
                zip.Save(BuildPath + "resources.zip");
            }

            using (var zip = new Ionic.Zip.ZipFile())
            {
                zip.AddDirectoryByName("script");
                zip.AddFile(outp, "script");
                zip.AddDirectoryByName("images");
                zip.AddDirectory(ResPath, "images");
                zip.Save(OutPath + Name + ".modpkg");
            }
        }
Beispiel #6
0
        /// <summary>
        /// Save a Package in to Filesystem
        /// </summary>
        /// <param name="filename">Suggested Extension: .xpkg</param>
        /// <param name="pkg">The saving Package</param>
        public static void Save(string filename, Package pkg)
        {
            using(var z = new ZipFile())
            {
                var content = z.AddDirectoryByName("content");
                var res = z.AddDirectoryByName("res");

                foreach (var r in pkg.XamlFiles)
                {
                    z.AddEntry($"content/{r.Key}", r.Value);
                }
                foreach (var r in pkg.Ressources)
                {
                    z.AddEntry($"res/{r.Key}", r.Value);
                }

                z.AddEntry("meta.xaml", XamlServices.Save(pkg.Meta));

                z.Save(filename);
            }
        }
Beispiel #7
0
		public static ZipFile CreateZipFile(string path, ZipFile zip, List<Attachment> files, string userName)
		{
			//var zip = new ZipFile(Encoding.UTF8);
			zip.AddDirectoryByName(userName);
			foreach (var fileName in files)
			{
				if (File.Exists(path + fileName.PathName + "//" + fileName.FileName))
				{
					zip.AddFile(path + fileName.PathName + "//" + fileName.FileName, userName).FileName = "\\" + userName  + "\\" + fileName.Name;
				}
			}

			return zip;
		}
Beispiel #8
0
        /// <summary>
        /// สำหรับ Zip ไฟล์และ Download
        /// </summary>
        /// <param name="httpResponse">Response ของ Page</param>
        /// <param name="reqDate">วันที่ต้องการ Download</param>
        /// <param name="tempFolder">Temp Folder</param>
        public void DownloadLicenseZip(System.Web.HttpResponse httpResponse, DateTime reqDate, string tempFolder)
        {
            //เตรียม Directory และ ไฟล์ที่ต้องการ Download
            string dir = InitRequestLicenseFileToDownload(tempFolder, reqDate);

            //สำหรับเก็บ Folder ที่ต้อง Zip เพื่อวนหาไฟล์ใน Folder
            List <string> list = new List <string>();

            list.Add(dir);

            //วนหา Folder ที่ต้อง Zip และ SubFolder ที่อยู่ภายใน
            GetAllFiles(list, dir);

            string folderName = string.Empty;

            //สร้าง  Instantce Zip
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
            {
                //กำหนด Option Endcode
                zip.AlternateEncodingUsage = ZipOption.AsNecessary;

                //วนเ Folder และ SubFolder
                for (int i = 0; i < list.Count; i++)
                {
                    //Folder ปัจจุบัน
                    DirectoryInfo dInfo = new DirectoryInfo(list[i]);
                    folderName += (i == 0 ? "" : "\\") + dInfo.Name;

                    //สร้าง Folder ใน Zip
                    zip.AddDirectoryByName(folderName);

                    //วน Add File ใน Folder
                    foreach (string f in Directory.GetFiles(list[i]))
                    {
                        zip.AddFile(f, folderName);
                    }
                }


                httpResponse.Clear();
                httpResponse.BufferOutput = false;
                string zipName = String.Format("{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
                httpResponse.ContentType = "application/zip";
                httpResponse.AddHeader("content-disposition", "attachment; filename=" + zipName);
                zip.Save(httpResponse.OutputStream);
                httpResponse.End();
            }
        }
Beispiel #9
0
        /// <summary>
        /// Writes a Fiddler session to SAZ.
        /// Written by Eric Lawrence (http://www.ericlawrence.com)
        /// THIS CODE SAMPLE & SOFTWARE IS LICENSED "AS-IS." YOU BEAR THE RISK OF USING IT. MICROSOFT GIVES NO EXPRESS WARRANTIES, GUARANTEES OR CONDITIONS. 
        /// </summary>
        /// <param name="sFilename"></param>
        /// <param name="arrSessions"></param>
        /// <param name="sPassword"></param>
        /// <returns></returns>
        public static bool WriteSessionArchive(string sFilename, Session[] arrSessions, string sPassword)
        {
            const string S_VER_STRING = "2.8.9";
            if ((null == arrSessions || (arrSessions.Length < 1))) {
                return false;
            }

            try {
                if (File.Exists(sFilename)) {
                    File.Delete(sFilename);
                }

                using (var oZip = new ZipFile()) {
                    oZip.AddDirectoryByName("raw");

                    if (!String.IsNullOrEmpty(sPassword)) {
                        if (CONFIG.bUseAESForSAZ) {
                            oZip.Encryption = EncryptionAlgorithm.WinZipAes256;
                        }
                        oZip.Password = sPassword;
                    }

                    oZip.Comment = "FiddlerCore SAZSupport (v" + S_VER_STRING + ") Session Archive. See http://www.fiddler2.com";

                    int iFileNumber = 1;
                    foreach (var oSession in arrSessions) {
                        var delegatesCopyOfSession = oSession;

                        string sBaseFilename = @"raw\" + iFileNumber.ToString("0000");
                        string sRequestFilename = sBaseFilename + "_c.txt";
                        string sResponseFilename = sBaseFilename + "_s.txt";
                        string sMetadataFilename = sBaseFilename + "_m.xml";

                        oZip.AddEntry(sRequestFilename, (sn, strmToWrite) => delegatesCopyOfSession.WriteRequestToStream(false, true, strmToWrite));
                        oZip.AddEntry(sResponseFilename, (sn, strmToWrite) => delegatesCopyOfSession.WriteResponseToStream(strmToWrite, false));
                        oZip.AddEntry(sMetadataFilename, (sn, strmToWrite) => delegatesCopyOfSession.WriteMetadataToStream(strmToWrite));

                        iFileNumber++;
                    }

                    oZip.Save(sFilename);
                }

                return true;
            } catch (Exception) {
                return false;
            }
        }
Beispiel #10
0
 private void AddScripts(ZipFile zip, InputAction inputAction)
 {
     foreach (var scriptSequenceItem in inputAction.ScriptSequences)
     {
         var inputScript =
             scriptProvider.Scripts.FirstOrDefault(s => s.Name == scriptSequenceItem.ScriptName);
         if (inputScript == null)
             continue;
         zip.AddDirectoryByName(KeySndrApp.ScriptsFolderName + "\\Sources");
         foreach (var sourceFile in inputScript.SourceFiles)
         {
             zip.AddEntry(KeySndrApp.ScriptsFolderName + "\\Sources\\" + sourceFile.FileName, sourceFile.Contents);
         }
         zip.AddEntry(KeySndrApp.ScriptsFolderName + "\\" + inputScript.FileName, JsonSerializer.Serialize(inputScript));
     }
 }
        public void DownloadLocal(HttpProcessor p)
        {
            try
            {
                p.writeSuccess("application/octet-stream");
                p.outputStreamWriter.WriteLine("Content-Disposition: attachment;filename=\"test.mxf\"");
                Console.WriteLine(": Start transfer file");
                long total = 0;
                //String fileName = p.httpHeaders["X-File-Name"].ToString();
                FileInfo fi = new FileInfo("C:/0003QS.MXF");
                if (!fi.Exists)
                {
                    throw new Exception("File not found");
                }
                long contentSize = fi.Length;
                using (ZipFile zip = new ZipFile())
                {
                    zip.UseZip64WhenSaving = Zip64Option.Always;
                    zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                    ZipEntry files = zip.AddDirectoryByName("Files");
                    zip.AddEntry("Files/0002D000.MXF", new FileStream("C:/0002D000.MXF", FileMode.Open, FileAccess.Read));
                    zip.AddEntry("Files/0002D002.MXF", new FileStream("C:/0002D000.MXF", FileMode.Open, FileAccess.Read));
                    zip.Save(p.outputStream);
                }
                //FileStream stream = new FileStream("C:/0003QS.MXF", FileMode.Open, FileAccess.Read);
                //byte[] buf = new byte[BUF_SIZE];
                //int numread = stream.Read(buf, 0,BUF_SIZE);
                //while (numread > 0 && contentSize>0)
                //{
                //    p.outputStream.Write(buf, 0, numread);
                //    total += numread;
                //    contentSize -= numread;
                //    numread = stream.Read(buf, 0, (int)Math.Min(contentSize,BUF_SIZE));
                //}

                Console.WriteLine(": Completed transfer file. " + total);
                //p.outputStreamWriter.WriteLine("{\"Status\":\"Success\",\"Size\":" + total + "}");
            }
            catch (Exception ex)
            {
                Console.WriteLine(": Error transfer file. ");
                p.writeSuccess();
                p.outputStreamWriter.WriteLine("{\"Status\":\"Failed\",\"Message\":\"" + ex.Message + "\"}");
            }
        }
 protected void DownloadFiles(object sender, EventArgs e)
 {
     using (ZipFile zip = new ZipFile())
     {
         zip.AlternateEncodingUsage = ZipOption.AsNecessary;
         zip.AddDirectoryByName("Files");
         foreach (GridViewRow row in GridView1.Rows)
         {
             if ((row.FindControl("chkSelect") as CheckBox).Checked)
             {
                 string filePath = (row.FindControl("lblFilePath") as Label).Text;
                 zip.AddFile(filePath, "Files");
             }
         }
         Response.Clear();
         Response.BufferOutput = false;
         string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
         Response.ContentType = "application/zip";
         Response.AddHeader("content-disposition", "attachment; filename=" + zipName);  
         zip.Save(Response.OutputStream);
         Response.End();
     }
 }
        public void Extended_CheckZip1()
        {
            string[] dirNames = { "", Path.GetFileName(Path.GetRandomFileName()) };

            string textToEncode =
                "Pay no attention to this: " +
                "We've read in the regular entry header, the extra field, and any  " +
                "encryption header.  The pointer in the file is now at the start of " +
                "the filedata, which is potentially compressed and encrypted.  Just " +
                "ahead in the file, there are _CompressedFileDataSize bytes of data, " +
                "followed by potentially a non-zero length trailer, consisting of " +
                "optionally, some encryption stuff (10 byte MAC for AES), " +
                "and then the bit-3 trailer (16 or 24 bytes). ";

            for (int i = 0; i < crypto.Length; i++)
            {
                for (int j = 0; j < z64.Length; j++)
                {
                    for (int k = 0; k < dirNames.Length; k++)
                    {
                        string zipFile = String.Format("Extended-CheckZip1-{0}.{1}.{2}.zip", i, j, k);
                        string password = Path.GetRandomFileName();

                        TestContext.WriteLine("=================================");
                        TestContext.WriteLine("Creating {0}...", Path.GetFileName(zipFile));

                        using (var zip = new ZipFile())
                        {
                            zip.Comment = String.Format("Encryption={0}  Zip64={1}  pw={2}",
                                                        crypto[i].ToString(), z64[j].ToString(), password);
                            if (crypto[i] != EncryptionAlgorithm.None)
                            {
                                TestContext.WriteLine("Encryption({0})  Zip64({1}) pw({2})",
                                                      crypto[i].ToString(), z64[j].ToString(), password);
                                zip.Encryption = crypto[i];
                                zip.Password = password;
                            }
                            else
                                TestContext.WriteLine("Encryption({0})  Zip64({1})",
                                                      crypto[i].ToString(), z64[j].ToString());

                            zip.UseZip64WhenSaving = z64[j];
                            if (!String.IsNullOrEmpty(dirNames[k]))
                                zip.AddDirectoryByName(dirNames[k]);
                            zip.AddEntry(Path.Combine(dirNames[k], "File1.txt"), textToEncode);
                            zip.Save(zipFile);
                        }

                        BasicVerifyZip(zipFile, password);
                        TestContext.WriteLine("Checking zip...");
                        using (var sw = new StringWriter())
                        {
                            bool result = FileSystemZip.CheckZip(zipFile, false, sw);
                            Assert.IsTrue(result, "Zip ({0}) does not check OK", zipFile);
                            var msgs = sw.ToString().Split('\n');
                            foreach (var msg in msgs)
                                TestContext.WriteLine("{0}", msg);
                        }
                    }
                }
            }
        }
Beispiel #14
0
        void _Zip64_Over65534Entries(Zip64Option z64option,
                                            EncryptionAlgorithm encryption,
                                            Ionic.Zlib.CompressionLevel compression)
        {
            // Emitting a zip file with > 65534 entries requires the use of ZIP64 in
            // the central directory.
            int numTotalEntries = _rnd.Next(4616)+65534;
            //int numTotalEntries = _rnd.Next(461)+6534;
            //int numTotalEntries = _rnd.Next(46)+653;
            string enc = encryption.ToString();
            if (enc.StartsWith("WinZip")) enc = enc.Substring(6);
            else if (enc.StartsWith("Pkzip")) enc = enc.Substring(0,5);
            string zipFileToCreate = String.Format("Zip64.ZF_Over65534.{0}.{1}.{2}.zip",
                                                   z64option.ToString(),
                                                   enc,
                                                   compression.ToString());

            _testTitle = String.Format("ZipFile #{0} 64({1}) E({2}), C({3})",
                                       numTotalEntries,
                                       z64option.ToString(),
                                       enc,
                                       compression.ToString());
            _txrx = TestUtilities.StartProgressMonitor(zipFileToCreate,
                                                       _testTitle,
                                                       "starting up...");

            _txrx.Send("pb 0 max 4"); // 3 stages: AddEntry, Save, Verify
            _txrx.Send("pb 0 value 0");

            string password = Path.GetRandomFileName();

            string statusString = String.Format("status Encrypt:{0} Compress:{1}...",
                                                enc,
                                                compression.ToString());

            int numSaved = 0;
            var saveProgress = new EventHandler<SaveProgressEventArgs>( (sender, e) => {
                    switch (e.EventType)
                    {
                        case ZipProgressEventType.Saving_Started:
                        _txrx.Send("status saving...");
                        _txrx.Send("pb 1 max " + numTotalEntries);
                        numSaved= 0;
                        break;

                        case ZipProgressEventType.Saving_AfterWriteEntry:
                        numSaved++;
                        if ((numSaved % 128) == 0)
                        {
                            _txrx.Send("pb 1 value " + numSaved);
                            _txrx.Send(String.Format("status Saving entry {0}/{1} ({2:N0}%)",
                                                     numSaved, numTotalEntries,
                                                     numSaved / (0.01 * numTotalEntries)
                                                     ));
                        }
                        break;

                        case ZipProgressEventType.Saving_Completed:
                        _txrx.Send("status Save completed");
                        _txrx.Send("pb 1 max 1");
                        _txrx.Send("pb 1 value 1");
                        break;
                    }
                });

            string contentFormatString =
                "This is the content for entry #{0}.\r\n\r\n" +
                "AAAAAAA BBBBBB AAAAA BBBBB AAAAA BBBBB AAAAA\r\n"+
                "AAAAAAA BBBBBB AAAAA BBBBB AAAAA BBBBB AAAAA\r\n";
            _txrx.Send(statusString);
            int dirCount= 0;
            using (var zip = new ZipFile())
            {
                _txrx.Send(String.Format("pb 1 max {0}", numTotalEntries));
                _txrx.Send("pb 1 value 0");

                zip.Password = password;
                zip.Encryption = encryption;
                zip.CompressionLevel = compression;
                zip.SaveProgress += saveProgress;
                zip.UseZip64WhenSaving = z64option;
                // save space when saving the file:
                zip.EmitTimesInWindowsFormatWhenSaving = false;
                zip.EmitTimesInUnixFormatWhenSaving = false;

                // add files:
                for (int m=0; m<numTotalEntries; m++)
                {
                    if (_rnd.Next(7)==0)
                    {
                        string entryName = String.Format("{0:D5}", m);
                        zip.AddDirectoryByName(entryName);
                        dirCount++;
                    }
                    else
                    {
                        string entryName = String.Format("{0:D5}.txt", m);
                        if (_rnd.Next(12)==0)
                        {
                            string contentBuffer = String.Format(contentFormatString, m);
                            byte[] buffer = System.Text.Encoding.ASCII.GetBytes(contentBuffer);
                            zip.AddEntry(entryName, contentBuffer);
                        }
                        else
                            zip.AddEntry(entryName, Stream.Null);
                    }

                    if (m % 1024 == 0)
                    {
                        _txrx.Send("pb 1 value " + m);
                        string msg = String.Format("status adding entry {0}/{1}  ({2:N0}%)",
                                            m, numTotalEntries, (m/(0.01*numTotalEntries)));
                        _txrx.Send(msg);
                    }
                }

                _txrx.Send("pb 0 step");
                _txrx.Send(statusString + " Saving...");
                zip.Save(zipFileToCreate);
            }

            _txrx.Send("pb 0 step");
            _txrx.Send("pb 1 value 0");
            _txrx.Send("status Reading...");

            // verify the zip by unpacking.
            _numFilesToExtract = numTotalEntries;
            _numExtracted= 1;
            _pb1Set = false;
            verb = "verify";
            BasicVerifyZip(zipFileToCreate, password, false, Zip64ExtractProgress);

            _txrx.Send("pb 0 step");
            _txrx.Send("status successful extract, now doing final count...");
            _txrx.Send("pb 1 value 0");
            Assert.AreEqual<int>(numTotalEntries-dirCount,
                                 TestUtilities.CountEntries(zipFileToCreate));
            _txrx.Send("pb 0 step");
        }
        public ZipFileResult Solutions(int id, bool compete)
        {
            var contest = this.Data.Contests.GetById(id);
            var problems = contest.Problems.OrderBy(x => x.Name).ToList();
            var participants =
                this.Data.Participants.All()
                    .Where(x => x.ContestId == id && x.IsOfficial == compete)
                    .Select(
                        x => new { x.Id, x.User.UserName, x.User.UserSettings.FirstName, x.User.UserSettings.LastName, })
                    .ToList()
                    .OrderBy(x => x.UserName);

            // Prepare file comment
            var fileComment = new StringBuilder();
            fileComment.AppendLine(string.Format("{1} submissions for {0}", contest.Name, compete ? "Contest" : "Practice"));
            fileComment.AppendLine(string.Format("Number of participants: {0}", participants.Count()));
            fileComment.AppendLine();
            fileComment.AppendLine("Problems:");
            foreach (var problem in problems)
            {
                fileComment.AppendLine(
                    string.Format(
                        "{0} - {1} points, time limit: {2:0.000} sec., memory limit: {3:0.00} MB",
                        problem.Name,
                        problem.MaximumPoints,
                        problem.TimeLimit / 1000.0,
                        problem.MemoryLimit / 1024.0 / 1024.0));
            }

            // Prepare zip file
            var file = new ZipFile
            {
                Comment = fileComment.ToString(),
                AlternateEncoding = Encoding.UTF8,
                AlternateEncodingUsage = ZipOption.AsNecessary
            };

            // Add participants solutions
            foreach (var participant in participants)
            {
                // Create directory with the participants name
                var directoryName =
                    string.Format("{0} ({1} {2})", participant.UserName, participant.FirstName, participant.LastName)
                        .ToValidFilePath();
                var directory = file.AddDirectoryByName(directoryName);

                foreach (var problem in problems)
                {
                    // Find submission
                    var bestSubmission =
                        this.Data.Submissions.All()
                            .Where(
                                submission =>
                                submission.ParticipantId == participant.Id && submission.ProblemId == problem.Id)
                            .OrderByDescending(submission => submission.Points)
                            .ThenByDescending(submission => submission.Id)
                            .FirstOrDefault();

                    // Create file if submission exists
                    if (bestSubmission != null)
                    {
                        var fileName =
                            string.Format("{0}.{1}", problem.Name, bestSubmission.SubmissionType.FileNameExtension)
                                .ToValidFileName();

                        byte[] content;
                        if (bestSubmission.IsBinaryFile)
                        {
                            content = bestSubmission.Content;
                        }
                        else
                        {
                            content = bestSubmission.ContentAsString.ToByteArray();
                        }

                        var entry = file.AddEntry(string.Format("{0}\\{1}", directoryName, fileName), content);
                        entry.CreationTime = bestSubmission.CreatedOn;
                        entry.ModifiedTime = bestSubmission.CreatedOn;
                    }
                }
            }

            // Send file to the user
            var zipFileName = string.Format("{1} submissions for {0}.zip", contest.Name, compete ? "Contest" : "Practice");
            return new ZipFileResult(file, zipFileName);
        }
Beispiel #16
0
        public void _Internal_Streams_ZipInput_Encryption(int fodderOption, int fileReadOption)
        {
            byte[] buffer = new byte[2048];
            int n;

            int[] fileCounts = { 1,
                                 2,
                                 _rnd.Next(8) + 6,
                                 _rnd.Next(18) + 16,
                                 _rnd.Next(48) + 56 };

            for (int m = 0; m < fileCounts.Length; m++)
            {
                string password = TestUtilities.GenerateRandomPassword();
                string dirToZip = String.Format("trial{0:D2}", m);
                if (!Directory.Exists(dirToZip)) Directory.CreateDirectory(dirToZip);

                int fileCount = fileCounts[m];
                TestContext.WriteLine("=====");
                TestContext.WriteLine("Trial {0} filecount={1}", m, fileCount);

                var files = (new Func<string[]>( () => {
                                 if (fodderOption == 0)
                                 {
                                     // zero length files
                                     var a = new string[fileCount];
                                     for (int i = 0; i < fileCount; i++)
                                         a[i] = CreateZeroLengthFile(i, dirToZip);
                                     return a;
                                 }

                                 if (fodderOption == 1)
                                     return TestUtilities.GenerateFilesFlat(dirToZip, fileCount, 100, 72000);


                                 // mixed = some zero and some not
                                 var b = new string[fileCount];
                                 for (int i = 0; i < fileCount; i++)
                                 {
                                     if (_rnd.Next(3) == 0)
                                         b[i] = CreateZeroLengthFile(i, dirToZip);
                                     else
                                     {
                                         b[i] = Path.Combine(dirToZip, String.Format("nonzero{0:D4}.txt", i));
                                         TestUtilities.CreateAndFillFileText(b[i], _rnd.Next(60000) + 100);
                                     }
                                 }
                                 return b;
                             }))();


                for (int i = 0; i < crypto.Length; i++)
                {
                    EncryptionAlgorithm c = crypto[i];

                    string zipFileToCreate =
                        Path.Combine(TopLevelDir,
                                     String.Format("ZIS_Crypto.{0}.count.{1:D2}.{2}.zip",
                                                   c.ToString(), fileCounts[m], fodderOption));

                    // Create the zip archive
                    using (var zip = new ZipFile())
                    {
                        zip.Password = password;
                        zip.Encryption = c;
                        if (fodderOption > 2)
                        {
                            zip.AddDirectoryByName("subdir");
                            zip.AddDirectory(dirToZip, "subdir");
                        }
                        else
                            zip.AddDirectory(dirToZip);

                        zip.Save(zipFileToCreate);
                    }


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

                    // extract the files
                    string extractDir = String.Format("extract{0:D2}.{1:D2}", m, i);
                    TestContext.WriteLine("Extract to: {0}", extractDir);
                    Directory.CreateDirectory(extractDir);

                    var input = (new Func<ZipInputStream>( () => {
                                if (fileReadOption == 0)
                                {
                                    var raw = File.OpenRead(zipFileToCreate);
                                    return new ZipInputStream(raw);
                                }

                                return FileSystemZip.CreateInputStream(zipFileToCreate);
                            }))();

                    using (input)
                    {
                        // set password if necessary
                        if (crypto[i] != EncryptionAlgorithm.None)
                            input.Password = password;

                        ZipEntry e;
                        while ((e = input.GetNextEntry()) != null)
                        {
                            TestContext.WriteLine("entry: {0}", e.FileName);
                            string outputPath = Path.Combine(extractDir, e.FileName);
                            if (e.IsDirectory)
                            {
                                // create the directory
                                Directory.CreateDirectory(outputPath);
                            }
                            else
                            {
                                // emit the file
                                using (var output = File.Create(outputPath))
                                {
                                    while ((n = input.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        output.Write(buffer, 0, n);
                                    }
                                }
                            }
                        }
                    }

                    string[] filesUnzipped = (fodderOption > 2)
                        ? Directory.GetFiles(Path.Combine(extractDir, "subdir"))
                        : Directory.GetFiles(extractDir);

                    // Verify the number of files extracted
                    Assert.AreEqual<int>(files.Length, filesUnzipped.Length,
                                         "Incorrect number of files extracted. ({0}!={1})", files.Length, filesUnzipped.Length);
                }
            }
        }
Beispiel #17
0
 static void CreatePackageStructure(string packageDll, string outputFile, string dataDirectory)
 {
     if (File.Exists(outputFile)) {
         File.Delete(outputFile);
     }
     if (!string.IsNullOrEmpty(dataDirectory) && Directory.Exists(dataDirectory) == false) {
         Directory.CreateDirectory(dataDirectory);
     }
     using (ZipFile zip = new ZipFile(outputFile)) {
         zip.AddFile(packageDll, "\\");
         zip.AddEntry("Config.xml", CreatePackageConfigXml(packageDll).ToString());
         zip.AddEntry("FileList.xml", CreatePackageFileList(dataDirectory));
         if (!string.IsNullOrEmpty(dataDirectory) && Directory.GetFiles(dataDirectory, "*", SearchOption.AllDirectories).Length > 0) {
             Console.WriteLine("Adding data files to package...");
             string[] files = Directory.GetFiles(dataDirectory, "*", SearchOption.AllDirectories);
             for (int i = 0; i < files.Length; i++) {
                 if (!files[i].Contains(".svn")) {
                     zip.AddFile(files[i], "\\Files" + Path.GetDirectoryName(files[i].Replace(dataDirectory, "")));
                 }
             }
         } else {
             zip.AddDirectoryByName("Files");
         }
         Assembly assembly = Assembly.LoadFile(packageDll);
         Console.WriteLine("Adding references to package...");
         foreach (AssemblyName name in assembly.GetReferencedAssemblies()) {
             if (name.Name != "mscorlib" && name.Name != "System") {
                 zip.AddFile(Path.GetDirectoryName(packageDll) + "\\" + name.Name + ".dll", "\\");
             }
         }
         Console.WriteLine("Saving package...");
         zip.Save();
     }
 }
        public void Test_AddDirectoryByName_WithFiles()
        {
            Directory.SetCurrentDirectory(TopLevelDir);

            var dirsAdded = new System.Collections.Generic.List<String>();
            string password = TestUtilities.GenerateRandomPassword();
            string zipFileToCreate = Path.Combine(TopLevelDir, "Test_AddDirectoryByName_WithFiles.zip");
            using (ZipFile zip1 = new ZipFile())
            {
                string dirName = null;
                int T = 3 + _rnd.Next(4);
                for (int n = 0; n < T; n++)
                {
                    // nested directories
                    dirName = (n == 0) ? "root" :
                        Path.Combine(dirName, TestUtilities.GenerateRandomAsciiString(8));

                    zip1.AddDirectoryByName(dirName);
                    dirsAdded.Add(dirName.Replace("\\", "/") + "/");
                    if (n % 2 == 0) zip1.Password = password;
                    zip1.AddEntry(Path.Combine(dirName, new System.String((char)(n + 48), 3) + ".txt"), "Hello, Dolly!");
                    if (n % 2 == 0) zip1.Password = null;
                }
                zip1.Save(zipFileToCreate);
            }

            int entryCount = 0;
            using (ZipFile zip2 = FileSystemZip.Read(zipFileToCreate))
            {
                foreach (var e in zip2)
                {
                    TestContext.WriteLine("e: {0}", e.FileName);
                    if (e.IsDirectory)
                        Assert.IsTrue(dirsAdded.Contains(e.FileName), "Cannot find the expected directory.");
                    else
                    {
                        if ((entryCount - 1) % 4 == 0) e.Password = password;
                        string output = StreamToStringUTF8(e.OpenReader());
                        Assert.AreEqual<string>("Hello, Dolly!", output);
                    }
                    entryCount++;
                }
            }
            Assert.AreEqual<int>(dirsAdded.Count * 2, entryCount);
        }
        public void Test_AddDirectoryByName()
        {
            for (int n = 1; n <= 10; n++)
            {
                var dirsAdded = new System.Collections.Generic.List<String>();
                string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("Test_AddDirectoryByName{0:N2}.zip", n));
                using (ZipFile zip1 = new ZipFile())
                {
                    for (int i = 0; i < n; i++)
                    {
                        // create an arbitrary directory name, add it to the zip archive
                        string dirName = TestUtilities.GenerateRandomName(24);
                        zip1.AddDirectoryByName(dirName);
                        dirsAdded.Add(dirName + "/");
                    }
                    zip1.Save(zipFileToCreate);
                }


                int dirCount = 0;
                using (ZipFile zip2 = FileSystemZip.Read(zipFileToCreate))
                {
                    foreach (var e in zip2)
                    {
                        TestContext.WriteLine("dir: {0}", e.FileName);
                        Assert.IsTrue(dirsAdded.Contains(e.FileName), "Cannot find the expected entry");
                        Assert.IsTrue(e.IsDirectory);
                        dirCount++;
                    }
                }
                Assert.AreEqual<int>(n, dirCount);
            }
        }
        protected void DownloadFiles(List<string> files)
        {
            if (files.Count == 1)
            {

                FileInfo fileInfo = new FileInfo(files[0]);

                Response.Clear();
                Response.BufferOutput = false;
                string fileName = String.Format("ProjectSummary_{0}" + fileInfo.Extension, DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));

                if (fileInfo.Extension == ".pdf")
                    Response.ContentType = "application/pdf";

                if (fileInfo.Extension == ".ppt")
                    Response.ContentType = "application/powerpoint";

                if (fileInfo.Extension == ".pptx")
                    Response.ContentType = "application/powerpoint";

                Response.AddHeader("content-disposition", "attachment; filename=" + fileName);

                byte[] fileContent = System.IO.File.ReadAllBytes(files[0]);

                Response.OutputStream.Write(fileContent, 0, fileContent.Length);

                Response.End();
            }
            else {
                using (ZipFile zip = new ZipFile())
                {
                    zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                    zip.AddDirectoryByName("Project Summary Detail");
                    foreach (string filePath in files)
                    {
                        zip.AddFile(filePath, "Project Summary Detail");
                    }
                    Response.Clear();
                    Response.BufferOutput = false;
                    string fileName = String.Format("ProjectSummaryZip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
                    Response.ContentType = "application/zip";
                    Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
                    zip.Save(Response.OutputStream);
                    Response.End();
                }
            }
        }
Beispiel #21
0
        string CreateArchive(LearningItem LearningItem)
        {
            pb.IsIndeterminate = true;
            pb.Text =  Tx.T("Publish.Messages.Archive");

            string li_path = FileService.GetPathToLearningItem(LearningItem);
            string li_id = LearningItem.id.ToString();

            string archiveDirectory = Path.Combine(FileService.GetPathToTempFolder(), li_id);
            if (!Directory.Exists(archiveDirectory)) Directory.CreateDirectory(archiveDirectory);
            string archiveFile = "";
            
            archiveFile = Path.Combine(archiveDirectory,Constants.Store.LearningItemDatFileName);
            if (File.Exists(archiveFile)) File.Delete(archiveFile);

            using (ZipFile zip = new ZipFile())
            {
                //zip.AddDirectory(FileService.GetPathToLearningItem(LearningItem),LearningItem.id.ToString());
                
                // Main db file
                zip.AddFile(Path.Combine(li_path, Constants.Store.LearningItemFileName),li_id);
                
                // Cover
                string _cover = Path.Combine(li_path, LearningItem.CoverFile);
                if (File.Exists(_cover))
                {
                    zip.AddFile(_cover,li_id);
                }

                // Add dictionaries
                zip.AddDirectoryByName(Constants.Folders.Dictionaries);

                foreach(Subtitles subt in LearningItem.SubtitleCollection)
                {
                    if(subt.Dictionary != null)
                    {
                        string CurrentDictFolder = Constants.Folders.Dictionaries + @"/" + subt.Dictionary.id.ToString();
                        zip.AddDirectoryByName(CurrentDictFolder);
                        zip.AddDirectory(FileService.GetPathToDictionaryFolder(subt.Dictionary),CurrentDictFolder);
                    }
                }
                zip.Save(archiveFile);
            }

            return archiveFile;
        }
        public void CreateZipFiles()
        {
            //Delete old zipfiles
            if (Directory.Exists(zipDirectory))
            {
                Directory.Delete(zipDirectory, true);
            }
            Directory.CreateDirectory(zipDirectory);

            //Create empty zipfiles
            using (ZipOutputStream zos = new ZipOutputStream(zipDirectory + "\\ClientFiles.zip"))
            { }
            using (ZipOutputStream zos = new ZipOutputStream(zipDirectory + "\\ServerFiles.zip"))
            { }

            //Create list of resourcepacks
            List <string> rpackList = new List <string>();

            using (FileStream fs = File.Open(cd + "\\resourcepack\\distribute.txt", FileMode.Open))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    while (true)
                    {
                        string nextLine = sr.ReadLine();

                        if (nextLine != null)
                        {
                            rpackList.Add(nextLine);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }

            //Create client zipfile
            using (Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(zipDirectory + "\\ClientFiles.zip"))
            {
                //Add modpack folders
                foreach (string folder in Directory.GetDirectories(cd + "\\modpack", "*", SearchOption.AllDirectories))
                {
                    if (zip.ContainsEntry(folder))
                    {
                        zip.RemoveEntry(folder);
                    }
                    zip.AddDirectoryByName(folder.Replace(cd + "\\modpack", ""));
                }
                //Add resourcepacks
                foreach (string file in Directory.GetFiles(cd + "\\resourcepack", "*.zip", SearchOption.TopDirectoryOnly))
                {
                    if (rpackList.Contains(Path.GetFileName(file)))
                    {
                        if (zip.ContainsEntry(file))
                        {
                            zip.RemoveEntry(file);
                        }
                        zip.AddFile(file, file.Replace(Path.GetFileName(file), "").Replace(cd + "\\resourcepack", "resourcepacks"));
                    }
                }
                //Add modpack files
                foreach (string file in Directory.GetFiles(cd + "\\modpack", "*.*", SearchOption.AllDirectories))
                {
                    if ((Main.acces.includeOptionsBox.Checked || (!file.Contains("\\modpack\\options.txt") && !file.Contains("\\modpack\\optionsof.txt"))) && (Main.acces.includeDisabledBox.Checked || Path.GetExtension(file) != ".disabled") && file != cd + "\\modpack\\bin\\modpack.jar")
                    {
                        if (zip.ContainsEntry(file))
                        {
                            zip.RemoveEntry(file);
                        }
                        zip.AddFile(file, file.Replace(Path.GetFileName(file), "").Replace(cd + "\\modpack", ""));
                    }
                }

                //Add modpack.jar
                try
                {
                    string file      = cd + "\\plugins\\mergedjar\\modpack.jar";
                    string zipFolder = "bin";

                    if (zip.ContainsEntry(file))
                    {
                        zip.RemoveEntry(file);
                    }
                    zip.AddFile(file, zipFolder);
                }
                catch
                { }
                //Add idfixminus.jar
                if (File.Exists(cd + "\\plugins\\idfixer\\idfixminus.jar"))
                {
                    string file      = cd + "\\plugins\\idfixer\\idfixminus.jar";
                    string zipFolder = "mods";

                    if (zip.ContainsEntry(file))
                    {
                        zip.RemoveEntry(file);
                    }
                    zip.AddFile(file, zipFolder);
                }

                //Save zipfile
                bool succeed = false;
                while (!succeed)
                {
                    try
                    {
                        zip.Save();
                        succeed = true;
                    }
                    catch
                    { }
                }
            }

            //Create server zipfile
            using (Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(zipDirectory + "\\ServerFiles.zip"))
            {
                //Add server folders
                foreach (string folder in Directory.GetDirectories(cd + "\\tests\\ServerBuild", "*", SearchOption.AllDirectories))
                {
                    if (zip.ContainsEntry(folder))
                    {
                        zip.RemoveEntry(folder);
                    }
                    zip.AddDirectoryByName(folder.Replace(cd + "\\tests\\ServerBuild", ""));
                }
                //Add server files
                foreach (string file in Directory.GetFiles(cd + "\\tests\\ServerBuild", "*.*", SearchOption.AllDirectories))
                {
                    if (zip.ContainsEntry(file))
                    {
                        zip.RemoveEntry(file);
                    }
                    zip.AddFile(file, file.Replace(Path.GetFileName(file), "").Replace(cd + "\\tests\\ServerBuild", ""));
                }

                //Save zipfile
                bool succeed = false;
                while (!succeed)
                {
                    try
                    {
                        zip.Save();
                        succeed = true;
                    }
                    catch
                    { }
                }
            }
        }
Beispiel #23
0
        public ActionResult Download(int? id)
        {
            //string path = HttpContext.Server.MapPath("~/DOCS/");
            try
            {
                var list = new GedEntities().DOCUMENTOS.Where(d => d.DOC_PROC_ID == id).ToList();
                if (list.Count == 0)
                {
                    throw new Exception("Não existe documentos para download.");
                }

                using (ZipFile zip = new ZipFile())
                {
                    zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                    //zip.AddDirectoryByName("Files");
                    zip.AddDirectoryByName("DOCS_" + id.ToString());
                    foreach (var doc in list)
                    {
                        // Get every file size
                        //byte[] fileBytes = System.IO.File.ReadAllBytes(Server.MapPath("~/DOCS/"+doc.DOC_ARQUIVO));
                        // Get every file path
                        string filePath = Server.MapPath("~/DOCS/" + doc.DOC_ARQUIVO);
                        //zip.AddFile(filePath, "Files");
                        zip.AddFile(filePath, "DOCS_" + id.ToString());
                    }
                    Response.Clear();
                    Response.BufferOutput = false;
                    //string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
                    string zipName = String.Format("Zip_DOCS_{0}.zip", id.ToString());
                    Response.ContentType = "application/zip";
                    Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
                    zip.Save(Response.OutputStream);
                    Response.End();
                }
            }
            catch(Exception ex)
            {
                TempData["MsgErro"] = "Erro, " + ex.Message;
            }
            return RedirectToAction("Documentos", new { procID=id });
        }
Beispiel #24
0
        /// <summary>
        /// Exports data to a KMZ file.
        /// </summary>
        /// <param name="tempBasePath">A temporary path where files creatred during the export will reside. This path should not exist before calling this method. The path is deleted when this method completes.</param>
        public void ExportKmz(string tempBasePath)
        {
            LogUtil.LogDebug("Started");
              // 1. create temp directories and the kmz file
              temporaryBasePath = tempBasePath;
              Directory.CreateDirectory(temporaryBasePath);
              Directory.CreateDirectory(temporaryBasePath + @"files\");
              kmzFile = new ZipFile();
              kmzFile.AddDirectoryByName("files");

              // 2. create ground overlay image streams for each document
              LogUtil.LogDebug("Creating overlays");
              var groundOverlayCount = 0;
              GroundOverlays = new Dictionary<KmlExportDocument, KmlGroundOverlay>();
              foreach (var document in kmlExportDocuments)
              {
            if (KmlProperties.MapType != KmlExportMapType.None)
            {
              var fileName = temporaryBasePath + @"files\o" + groundOverlayCount + "." + document.ImageExporter.Properties.EncodingInfo.Encoder.MimeType.Replace("image/", ""); // NOTE: this assumes that the mime type matches the file extension
              using (var imageStream = new FileStream(fileName, FileMode.Create))
              {
            document.ImageExporter.OutputStream = imageStream;
            switch (KmlProperties.MapType)
            {
              case KmlExportMapType.Map:
                document.ImageExporter.Properties.RouteDrawingMode = Document.RouteDrawingMode.None;
                break;
              case KmlExportMapType.MapAndRoute:
                document.ImageExporter.Properties.RouteDrawingMode = Document.RouteDrawingMode.Extended;
                break;
            }
            document.ImageExporter.Export();

            GroundOverlays.Add(document, new KmlGroundOverlay(fileName, KmlGroundOverlay.GroundOverlayType.File));
            groundOverlayCount++;
              }
            }
              }

              // 3. generate kml document
              LogUtil.LogDebug("Generating kml document");
              var tempKmlFileName = temporaryBasePath + "doc.kml";
              using (var kmlStream = new FileStream(tempKmlFileName, FileMode.Create))
              {
            var writerSettings = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true, IndentChars = "  " };
            using (var writer = XmlWriter.Create(kmlStream, writerSettings))
            {
              CreateKml(writer);
              writer.Close();
              kmzFile.AddFile(tempKmlFileName, "");
            }
              }
              kmzFile.Save(OutputStream);
              kmzFile.Dispose();

              // 4. delete temp directory and its content
              LogUtil.LogDebug("Deleting temp dir");
              Directory.Delete(temporaryBasePath, true);
              LogUtil.LogDebug("Finished");
        }
        public void Extended_CheckZip2()
        {
            string textToEncode =
                "Pay no attention to this: " +
                "We've read in the regular entry header, the extra field, and any " +
                "encryption header. The pointer in the file is now at the start of " +
                "the filedata, which is potentially compressed and encrypted.  Just " +
                "ahead in the file, there are _CompressedFileDataSize bytes of " +
                "data, followed by potentially a non-zero length trailer, " +
                "consisting of optionally, some encryption stuff (10 byte MAC for " +
                "AES), and then the bit-3 trailer (16 or 24 bytes). " +
                " " +
                "The encryption can be either PKZIP 2.0 (weak) encryption, or " +
                "WinZip-compatible AES encryption, which is considered to be " +
                "strong and for that reason is preferred.  In the WinZip AES " +
                "option, there are two different keystrengths supported: 128 bits " +
                "and 256 bits. " +
                " " +
                "The extra field, which I mentioned previously, specifies " +
                "additional metadata about the entry, which is strictly-speaking, " +
                "optional. These data are things like high-resolution timestamps, " +
                "data sizes that exceed 2^^32, and other encryption " +
                "possibilities.  In each case the library that reads a zip file " +
                "needs to be able to correctly deal with the various fields, " +
                "validating the values within them. " +
                " " +
                "Now, cross all that with the variety of usage patterns - creating a " +
                "zip, or reading, or extracting, or updating, or updating several " +
                "times. And also, remember that the metadata may change during " +
                "updates: an application can apply a password where none was used " +
                "previously, or it may wish to remove an entry from the zip entirely. " +
                " " +
                "The huge variety of combinations of possibilities is what makes " +
                "testing a zip library so challenging. " ;
            
            string fileToZip = Path.Combine(SourceDir, TestUtilities.GetBinDir("Zip.Portable.Tests"), "Zip.Portable.dll");

            for (int i = 0; i < crypto.Length; i++)
            {
                for (int j = 0; j < z64.Length; j++)
                {
                    string zipFile = String.Format("Extended-CheckZip2-{0}.{1}.zip", i, j);
                    string password = Path.GetRandomFileName();

                    TestContext.WriteLine("=================================");
                    TestContext.WriteLine("Creating {0}...", Path.GetFileName(zipFile));

                    string dir = Path.GetRandomFileName();
                    using (var zip = new ZipFile())
                    {
                        zip.Comment = String.Format("Encryption={0}  Zip64={1}  pw={2}",
                                                    crypto[i].ToString(), z64[j].ToString(), password);

                        zip.Encryption = crypto[i];
                        if (crypto[i] != EncryptionAlgorithm.None)
                        {
                            TestContext.WriteLine("Encryption({0})  Zip64({1}) pw({2})",
                                                  crypto[i].ToString(), z64[j].ToString(), password);
                            zip.Password = password;
                        }
                        else
                            TestContext.WriteLine("Encryption({0})  Zip64({1})",
                                                  crypto[i].ToString(), z64[j].ToString());

                        zip.UseZip64WhenSaving = z64[j];
                        int N = _rnd.Next(11) + 5;
                        for (int k = 0; k < N; k++)
                            zip.AddDirectoryByName(Path.GetRandomFileName());

                        zip.AddEntry("File1.txt", textToEncode);
                        zip.AddFile(fileToZip, Path.GetRandomFileName());
                        zip.Save(zipFile);
                    }

                    BasicVerifyZip(zipFile, password, false);

                    TestContext.WriteLine("Checking zip...");

                    using (var sw = new StringWriter())
                    {
                        bool result = FileSystemZip.CheckZip(zipFile, false, sw);
                        Assert.IsTrue(result, "Zip ({0}) does not check OK", zipFile);
                        var msgs = sw.ToString().Split('\n');
                        foreach (var msg in msgs)
                            TestContext.WriteLine("{0}", msg);
                    }
                    TestContext.WriteLine("OK");
                    TestContext.WriteLine("");
                }
            }
        }
        public void ReadZip_DirectoryBitSetForEmptyDirectories()
        {
            string zipFileToCreate = Path.Combine(TopLevelDir, "ReadZip_DirectoryBitSetForEmptyDirectories.zip");

            using (ZipFile zip1 = new ZipFile())
            {
                zip1.AddDirectoryByName("Directory1");
                // must retrieve with a trailing slash.
                ZipEntry e1 = zip1["Directory1/"];
                Assert.AreNotEqual<ZipEntry>(null, e1);
                Assert.IsTrue(e1.IsDirectory,
                              "The IsDirectory property was not set as expected.");
                zip1.AddDirectoryByName("Directory2");
                zip1.AddEntry(Path.Combine("Directory2", "Readme.txt"), "This is the content");
                Assert.IsTrue(zip1["Directory2/"].IsDirectory,
                              "The IsDirectory property was not set as expected.");
                zip1.Save(zipFileToCreate);
                Assert.IsTrue(zip1["Directory1/"].IsDirectory,
                              "The IsDirectory property was not set as expected.");
            }

            // read the zip and retrieve the dir entries again
            using (ZipFile zip2 = FileSystemZip.Read(zipFileToCreate))
            {
                Assert.IsTrue(zip2["Directory1/"].IsDirectory,
                              "The IsDirectory property was not set as expected.");

                Assert.IsTrue(zip2["Directory2/"].IsDirectory,
                              "The IsDirectory property was not set as expected.");
            }

            // now specify dir names with backslash
            using (ZipFile zip3 = FileSystemZip.Read(zipFileToCreate))
            {
                Assert.IsTrue(zip3["Directory1\\"].IsDirectory,
                              "The IsDirectory property was not set as expected.");

                Assert.IsTrue(zip3["Directory2\\"].IsDirectory,
                              "The IsDirectory property was not set as expected.");

                Assert.IsNull(zip3["Directory1"]);
                Assert.IsNull(zip3["Directory2"]);
            }

        }
Beispiel #27
0
        private static bool WriteSessionArchive(string sFilename, Session[] arrSessions, string sPassword, bool bVerboseDialogs)
        {
            if ((null == arrSessions || (arrSessions.Length < 1)))
            {
                if (bVerboseDialogs)
                {
                    FiddlerApplication.Log.LogString("WriteSessionArchive - No Input. No sessions were provided to save to the archive.");
                }
                return false;
            }

            try
            {
                if (File.Exists(sFilename))
                {
                    File.Delete(sFilename);
                }

                ZipFile oZip = new ZipFile();
                // oZip.TempFolder = new MemoryFolder();
                oZip.AddDirectoryByName("raw");

#region PasswordProtectIfNeeded
                if (!String.IsNullOrEmpty(sPassword))
                {
                    if (CONFIG.bUseAESForSAZ)
                    {
                        oZip.Encryption = EncryptionAlgorithm.WinZipAes256;
                    }
                    oZip.Password = sPassword;
                }
#endregion PasswordProtectIfNeeded

                oZip.Comment = Fiddler.CONFIG.FiddlerVersionInfo + " " + GetZipLibraryInfo() + " Session Archive. See http://www.fiddler2.com";
                oZip.ZipError += new EventHandler<ZipErrorEventArgs>(oZip_ZipError);
#region ProcessEachSession
                int iFileNumber = 1;
                // Our format string must pad all session ids with leading 0s for proper sorting.
                string sFileNumberFormatter = ("D" + arrSessions.Length.ToString().Length);
               
                foreach (Session oSession in arrSessions)
                {
                    // If you don't make a copy of the session within the delegate's scope,
                    // you get a behavior different than what you'd expect.
                    // See http://blogs.msdn.com/brada/archive/2004/08/03/207164.aspx
                    // and http://blogs.msdn.com/oldnewthing/archive/2006/08/02/686456.aspx
                    // and http://blogs.msdn.com/oldnewthing/archive/2006/08/04/688527.aspx
                    Session delegatesCopyOfSession = oSession;

                    string sBaseFilename = @"raw\" + iFileNumber.ToString(sFileNumberFormatter);
                    string sRequestFilename = sBaseFilename + "_c.txt";
                    string sResponseFilename = sBaseFilename + "_s.txt";
                    string sMetadataFilename = sBaseFilename + "_m.xml";

                    oZip.AddEntry(sRequestFilename, new WriteDelegate(delegate(string sn, Stream strmToWrite)
                        {
                            delegatesCopyOfSession.WriteRequestToStream(false, true, strmToWrite);
                        })
                    );

                    oZip.AddEntry(sResponseFilename,
                        new WriteDelegate(delegate(string sn, Stream strmToWrite)
                        {
                            delegatesCopyOfSession.WriteResponseToStream(strmToWrite, false);
                        })
                    );

                    oZip.AddEntry(sMetadataFilename,
                        new WriteDelegate(delegate(string sn, Stream strmToWrite)
                        {
                            delegatesCopyOfSession.WriteMetadataToStream(strmToWrite);
                        })
                    );

                    iFileNumber++;
                }
#endregion ProcessEachSession
                oZip.Save(sFilename);

                return true;
            }
            catch (Exception eX)
            {
                FiddlerApplication.Log.LogString("WriteSessionArchive failed to save Session Archive. " + eX.Message);
                return false;
            }
        }
        public void Test_AddDirectoryByName_Nested()
        {
            Directory.SetCurrentDirectory(TopLevelDir);
            var dirsAdded = new System.Collections.Generic.List<String>();
            string zipFileToCreate = Path.Combine(TopLevelDir, "Test_AddDirectoryByName_Nested.zip");
            using (ZipFile zip1 = new ZipFile())
            {
                for (int n = 1; n <= 14; n++)
                {
                    string DirName = n.ToString();
                    for (int i = 0; i < n; i++)
                    {
                        // create an arbitrary directory name, add it to the zip archive
                        DirName = Path.Combine(DirName, TestUtilities.GenerateRandomAsciiString(11));
                    }
                    zip1.AddDirectoryByName(DirName);
                    dirsAdded.Add(DirName.Replace("\\", "/") + "/");
                }
                zip1.Save(zipFileToCreate);
            }

            int dirCount = 0;
            using (ZipFile zip2 = FileSystemZip.Read(zipFileToCreate))
            {
                foreach (var e in zip2)
                {
                    TestContext.WriteLine("dir: {0}", e.FileName);
                    Assert.IsTrue(dirsAdded.Contains(e.FileName), "Cannot find the expected directory.");
                    Assert.IsTrue(e.IsDirectory);
                    dirCount++;
                }
            }
            Assert.AreEqual<int>(dirsAdded.Count, dirCount);
        }
        private void zipFolder(CloudBlobClient blobClient, string basePrefix, string folderName, string zipDir, ref ZipFile zipFile)
        {
            zipDir = string.IsNullOrEmpty(zipDir) ? folderName : zipDir + "/" + folderName;
            zipFile.AddDirectoryByName(zipDir);
            var folderPrefix = basePrefix + StorageNamesEncoder.EncodeBlobName(folderName) + "/";

            var blobs = blobClient.ListBlobsWithPrefix(folderPrefix,
            new BlobRequestOptions() { BlobListingDetails = Microsoft.WindowsAzure.StorageClient.BlobListingDetails.Metadata, UseFlatBlobListing = false });
            foreach (var blob in blobs)
            {
                if (blob is CloudBlobDirectory)
                {
                    var dir = blob as CloudBlobDirectory;

                    var names = dir.Uri.ToString().Split('/');
                    for (var i = names.Length - 1; i >= 0; i--)
                    {
                        if (!string.IsNullOrEmpty(names[i]))
                        {
                            zipFolder(blobClient, folderPrefix, StorageNamesEncoder.DecodeBlobName(names[i]), zipDir, ref zipFile);
                            break;
                        }
                    }
                }
                if (blob is CloudBlob)
                {
                    var cloudBlob = blob as CloudBlob;
                    var subStr = cloudBlob.Uri.ToString().Substring(cloudBlob.Uri.ToString().IndexOf(folderPrefix) + folderPrefix.Length);
                    var index = subStr.LastIndexOf('/');
                    if (index < 0)
                    {
                        index = 0;
                    }

                    var subFolderName = subStr.Substring(0, index);
                    var fileName = subStr.Substring(index);
                    var bytes = cloudBlob.DownloadByteArray();
                    if (!string.IsNullOrEmpty(subFolderName))
                    {
                        zipFile.AddDirectoryByName(zipDir + "/" + StorageNamesEncoder.DecodeBlobName(subFolderName));
                    }
                    zipFile.AddEntry(zipDir + "/" + StorageNamesEncoder.DecodeBlobName(subStr), bytes);
                }
            }
        }
Beispiel #30
0
        public SubsystemAssembly GetAssembly(GetAssemblyParameterMessage message)
        {
            try
            {
                string assemblyDirLocation = AppDomain.CurrentDomain.BaseDirectory;
                List<string> dirList = new List<string>(Directory.GetDirectories(assemblyDirLocation));

                Stream stream = new MemoryStream();

                string name = dirList.Find(
                    delegate(string dirName)
                    {
                        return (dirName.Contains(message.SystemMode.ToString()));
                    });

                //if specified assembly doesn't exist then 
                //find one below the specified assembly level
                //e.g. if specified assembly is Engineer then look for
                // Maintenance, if not found then Supervisor, if not found
                // then Operator
                List<EnumSystemOperationMode> SearchCriteria = new List<EnumSystemOperationMode>();

                if (String.IsNullOrWhiteSpace(name))
                {
                    if (message.SystemMode == EnumSystemOperationMode.Engineer)
                    {
                        SearchCriteria.Add(EnumSystemOperationMode.Maintenance);
                    }

                    if (message.SystemMode == EnumSystemOperationMode.Maintenance ||
                        message.SystemMode == EnumSystemOperationMode.Engineer)
                    {
                        SearchCriteria.Add(EnumSystemOperationMode.Supervisor);
                    }

                    if (message.SystemMode == EnumSystemOperationMode.Supervisor ||
                        message.SystemMode == EnumSystemOperationMode.Engineer ||
                        message.SystemMode == EnumSystemOperationMode.Maintenance)
                    {
                        SearchCriteria.Add(EnumSystemOperationMode.Operator);
                    }

                    foreach (EnumSystemOperationMode criteria in SearchCriteria)
                    {
                        name = dirList.Find(
                        delegate(string dirName)
                        {
                            return (dirName.Contains(criteria.ToString()));
                        });

                        if (!String.IsNullOrWhiteSpace(name))
                        {
                            break;
                        }
                    }
                }

                if (!String.IsNullOrWhiteSpace(name))
                {
                    using (ZipFile zip = new ZipFile())
                    {
                        string[] files = Directory.GetFiles(name);

                        // changing this defalte threshold avoids corrupted files in the zipfile.
                        zip.ParallelDeflateThreshold = -1; 

                        zip.AddFiles(files, "");

                        // zip up resource directories as well
                        string[] directories = Directory.GetDirectories(name);
                        foreach (string subDir in directories)
                        {
                            try
                            {
                                // only add resource files for this local project. Exclude the L3.Cargo.Common.Dashboard.resources.dll
                                string[] resFiles = Directory.GetFiles(subDir);
                                zip.AddDirectoryByName(Path.GetFileName(subDir));
                                foreach (string resFile in resFiles)
                                {
                                    // Avoid adding the resource file for the Dashboard.
                                    // TODO: this string should come from somewhere
                                    if (!resFile.Contains("L3.Cargo.Common.Dashboard.resources.dll"))
                                    {
                                        zip.AddFile(resFile, Path.GetFileName(subDir));
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                string ex = e.Message;
                            }
                        }

                        zip.Save(stream);
                        stream.Seek(0, SeekOrigin.Begin);
                    }

                    OperationContext clientContext = OperationContext.Current;
                    clientContext.OperationCompleted += new EventHandler(delegate(object sender, EventArgs e)
                    {
                        if (stream != null)
                            stream.Dispose();
                    });

                    return new SubsystemAssembly(stream, m_aliasTag + "_" + m_assemblyTag + ".zip");
                }
                else
                    throw new FaultException(new FaultReason("File does not exist"));
            }
            catch (Exception exp)
            {
                throw new FaultException(new FaultReason(exp.Message));
            }
        }
Beispiel #31
0
 private void CreateFolders(ZipFile zip, bool hasView)
 {
     zip.AddDirectoryByName(KeySndrApp.ConfigurationsFolderName);
     zip.AddDirectoryByName(KeySndrApp.ScriptsFolderName);
     zip.AddDirectoryByName(KeySndrApp.MappingsFolderName);
     zip.AddDirectoryByName(KeySndrApp.MediaFolderName);
     if (hasView)
         zip.AddDirectoryByName(KeySndrApp.ViewsFolderName);
 }
Beispiel #32
0
        public void Password_UnsetEncryptionAfterSetPassword_wi13909_ZF()
        {
            // Verify that unsetting the Encryption property after
            // setting a Password results in no encryption being used.
            // This method tests ZipFile.
            string unusedPassword = TestUtilities.GenerateRandomPassword();
            int numTotalEntries = _rnd.Next(46)+653;
            string zipFileToCreate = "UnsetEncryption.zip";

            using (var zip = new ZipFile())
            {
                zip.Password = unusedPassword;
                zip.Encryption = EncryptionAlgorithm.None;

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

            BasicVerifyZip(zipFileToCreate);
        }
Beispiel #33
0
        private void SaveProjectAs(object sender, EventArgs e)
        {
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = Messages.kazOilMapProject; // Default file name
            dlg.DefaultExt = "";// Messages.kazOilMapExtension; // Default file extension
            dlg.Filter = Messages.kazOilMapFilter; // Filter files by extension

            Nullable<bool> result = dlg.ShowDialog();

            // Process open file dialog box results
            if (result == true)
            {
                // Open document
                string filename = dlg.FileName;
                string actualProjectName = System.IO.Path.GetFileNameWithoutExtension(filename);
                string filenameParentDir = System.IO.Path.GetDirectoryName(filename);

                // actual zipping
                using (ZipFile zip = new ZipFile())
                {
                    string dir = Utils.GetTempDirectory();

                    currentProject.paramz.Serialize(dir + System.IO.Path.DirectorySeparatorChar + Messages.kazOilMapMainXml);

                    // Debug(dir + System.IO.Path.DirectorySeparatorChar + Messages.kazOilMapMainXml);

                    zip.AddDirectory(dir);
                    zip.AddDirectoryByName("output");
                    zip.Save(filename);
                }
            }
        }
        private static void AddTreeToZip(RepositoryBrowser browser, string name, string path, ZipFile outputZip)
        {
            string referenceName;
            var treeNode = browser.BrowseTree(name, path, out referenceName);

            foreach (var item in treeNode)
            {
                if (item.IsLink)
                {
                    outputZip.AddDirectoryByName(Path.Combine(item.TreeName, item.Path));
                }
                else if (!item.IsTree)
                {
                    string blobReferenceName;
                    var model = browser.BrowseBlob(item.TreeName, item.Path, out blobReferenceName);
                    outputZip.AddEntry(Path.Combine(item.TreeName, item.Path), model.Data);
                }
                else
                {
                    // recursive call
                    AddTreeToZip(browser, item.TreeName, item.Path, outputZip);
                }
            }
        }
Beispiel #35
0
 protected void BuildEpubStructure()
 {
     file = new ZipFile();
     file.AddEntry("mimetype", Resources.Mimetype).CompressionLevel = CompressionLevel.None;
     if(!string.IsNullOrEmpty(Structure.Directories.ContentFolder)) file.AddDirectoryByName(Structure.Directories.ContentFolder);
     file.AddDirectoryByName(Structure.Directories.MetaInfFolder);
     if (!string.IsNullOrEmpty(Structure.Directories.ImageFolder)) file.AddDirectoryByName(Structure.Directories.ImageFolderFullPath);
     if (!string.IsNullOrEmpty(Structure.Directories.CssFolder)) file.AddDirectoryByName(Structure.Directories.CssFolderFullPath);
 }