public void UnicodeComment_wi10392()
        {
            const string zipFileToCreate = "UnicodeComment_wi10392.zip";
            const string cyrillicComment = "Hello, Привет";

            TestContext.WriteLine("{0}", zipFileToCreate);
            TestContext.WriteLine("==== creating zip");
            using (ZipFile zip1 = new ZipFile(System.Text.Encoding.UTF8))
            {
                zip1.Comment = cyrillicComment;
                zip1.AddEntry("entry", "this is the content of the added entry");
                zip1.Save(zipFileToCreate);
            }

            string comment2 = null;

            TestContext.WriteLine("==== checking zip");
            var options = new ReadOptions {
                Encoding = System.Text.Encoding.UTF8
            };

            using (ZipFile zip2 = FileSystemZip.Read(zipFileToCreate, options))
            {
                comment2 = zip2.Comment;
            }

            Assert.AreEqual <String>(cyrillicComment, comment2,
                                     "The comments are not equal.");
        }
Exemplo n.º 2
0
        public void Error_Read_EmptyZipFile()
        {
            string zipFileToRead = Path.Combine(TopLevelDir, "Read_BadFile.zip");
            string newFile       = Path.GetTempFileName();

            _FilesToRemove.Add(newFile);
            File.Move(newFile, zipFileToRead);
            newFile = Path.GetTempFileName();
            _FilesToRemove.Add(newFile);
            string fileToAdd = Path.Combine(TopLevelDir, "EmptyFile.txt");

            File.Move(newFile, fileToAdd);

            try
            {
                using (ZipFile zip = FileSystemZip.Read(zipFileToRead))
                {
                    zip.AddFile(fileToAdd, "");
                    zip.Save(zipFileToRead);
                }
            }
            catch (System.Exception exc1)
            {
                throw new ZipException("expected", exc1);
            }
        }
        private void _CheckUnicodeZip(string filename, int j)
        {
            int i = 0;

            // Verify that the filenames do, or do not, match the
            // names that were added.  They will match if unicode
            // was used (j!=1) or if the filename used was the first
            // in the formats list (k==0).
            using (ZipFile zip2 = FileSystemZip.Read(filename))
            {
                foreach (ZipEntry e in zip2)
                {
                    int    k     = i % miscNameFormats.Length;
                    string fname = String.Format(miscNameFormats[k], i);
                    if (j != 1 || k == 0)
                    {
                        Assert.AreEqual <String>(fname, e.FileName, "cycle ({0},{1},{2})", i, j, k);
                    }
                    else
                    {
                        Assert.AreNotEqual <String>(fname, e.FileName, "cycle ({0},{1},{2})", i, j, k);
                    }
                    i++;
                }
            }
        }
Exemplo n.º 4
0
        public void Password_CheckZipPassword_wi13664()
        {
            string[] passwords = { null,
                                   "Password!",
                                   TestUtilities.GenerateRandomPassword(),
                                   "_" };

            string dirToZip = Path.Combine(TopLevelDir, "zipthis");
            int    subdirCount;
            int    entries = TestUtilities.GenerateFilesOneLevelDeep
                                 (TestContext, "wi13664", dirToZip, null, out subdirCount);

            string[] filesToZip = Directory.GetFiles("zipthis", "*.*", SearchOption.AllDirectories);

            Assert.AreEqual <int>(filesToZip.Length, entries,
                                  "Incorrect number of entries in the directory.");

            for (int j = 0; j < passwords.Length; j++)
            {
                string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("Password_CheckZipPassword_wi13664-{0}.zip", j));

                // Create the zip archive
                using (ZipFile zip1 = new ZipFile())
                {
                    zip1.Password = passwords[j];
                    zip1.AddFiles(filesToZip, "", true);
                    zip1.Save(zipFileToCreate);
                }

                var r = FileSystemZip.CheckZipPassword(zipFileToCreate, passwords[j]);
                Assert.IsTrue(r, "Bad password in round {0}", j);
            }
        }
Exemplo n.º 5
0
        public void Progress_ReadFile()
        {
            Directory.SetCurrentDirectory(TopLevelDir);
            string zipFileToCreate = Path.Combine(TopLevelDir, "Progress_ReadFile.zip");
            string dirToZip        = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());

            var files = TestUtilities.GenerateFilesFlat(dirToZip);

            using (ZipFile zip = new ZipFile())
            {
                zip.AddFiles(files);
                zip.Save(zipFileToCreate);
            }

            int count = TestUtilities.CountEntries(zipFileToCreate);

            Assert.IsTrue(count > 0);

            var options = new ReadOptions {
                StatusMessageWriter = new StringWriter(),
                ReadProgress        = ReadProgress1
            };

            using (ZipFile zip = FileSystemZip.Read(zipFileToCreate, options))
            {
                // this should be fine
                zip.RemoveEntry(zip[1]);
                zip.Save(zipFileToCreate);
            }
            TestContext.WriteLine(options.StatusMessageWriter.ToString());
            Assert.AreEqual <Int32>(count, TestUtilities.CountEntries(zipFileToCreate) + 1);
        }
Exemplo n.º 6
0
        public void Error_UseOpenReaderWith_ZIS_wi10923()
        {
            string zipFileToCreate = "UseOpenReaderWith_ZIS.zip";

            CreateSmallZip(zipFileToCreate);

            // mixing OpenReader and ZipInputStream is a no-no!!
            int n;
            var buffer = new byte[2048];

            // Use OpenReader with ZipInputStream.
            // This must fail.
            TestContext.WriteLine("Reading with ZipInputStream");
            using (var zip = FileSystemZip.CreateInputStream(zipFileToCreate))
            {
                ZipEntry entry;
                while ((entry = zip.GetNextEntry()) != null)
                {
                    TestContext.WriteLine("  Entry: {0}", entry.FileName);
                    using (Stream file = entry.OpenReader())
                    {
                        while ((n = file.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            ;
                        }
                    }
                    TestContext.WriteLine("  -- OpenReader() is done. ");
                }
            }
        }
        private void _Internal_ReadZip(string zipFileToRead, string password, int expectedFilesExtracted)
        {
            Directory.SetCurrentDirectory(TopLevelDir);

            Assert.IsTrue(File.Exists(zipFileToRead), "The zip file '{0}' does not exist.", zipFileToRead);

            // extract all the files
            int    actualFilesExtracted = 0;
            string extractDir           = String.Format("Extract{0}", zipCount++);

            using (ZipFile zip2 = FileSystemZip.Read(zipFileToRead))
            {
                //zip2.Password = password;
                foreach (ZipEntry e in zip2)
                {
                    if (!e.IsDirectory)
                    {
                        if (password == "-null-")
                        {
                            e.Extract(extractDir);
                        }
                        else
                        {
                            e.ExtractWithPassword(extractDir, password);
                        }
                        actualFilesExtracted++;
                    }
                }
            }
            Assert.AreEqual <int>(expectedFilesExtracted, actualFilesExtracted);
        }
        public void Spanned_Resave_Extract()
        {
            TestContext.WriteLine("Creating fodder files... {0}",
                                  DateTime.Now.ToString("G"));
            var contentDir = CreateSomeFiles();
            var filesToAdd = new List <String>(Directory.GetFiles(contentDir));

            int[] segSizes = { 128, 256, 512 };

            // for various segment sizes
            for (int k = 0; k < segSizes.Length; k++)
            {
                string trialDir = String.Format("trial.{0}", k);
                Directory.CreateDirectory(trialDir);
                string zipFile1   = Path.Combine(trialDir, "InitialSave." + k + ".zip");
                string zipFile2   = Path.Combine(trialDir, "Updated." + k + ".zip");
                string extractDir = Path.Combine(trialDir, "extract");

                TestContext.WriteLine("");
                TestContext.WriteLine("Creating zip... T({0})...{1}", k, DateTime.Now.ToString("G"));
                using (var zip1 = new ZipFile())
                {
                    zip1.AddFiles(filesToAdd, "");
                    zip1.MaxOutputSegmentSize = segSizes[k] * 1024;
                    zip1.Save(zipFile1);
                }

                TestContext.WriteLine("");
                TestContext.WriteLine("Re-saving...");
                using (var zip2 = FileSystemZip.Read(zipFile1))
                {
                    zip2.MaxOutputSegmentSize = segSizes[k] * 1024;
                    zip2.Save(zipFile2);

                    // make sure we aren't accidentally using InitialSave.*.zip data
                    TestContext.WriteLine("");
                    TestContext.WriteLine("Deleting initial archive...");
                    string[] filesToDelete = Directory.GetFiles(trialDir, "InitialSave.*");
                    foreach (var file in filesToDelete)
                    {
                        File.Delete(file);
                    }

                    // this should be using the Updated.*.zip file stream
                    TestContext.WriteLine("");
                    TestContext.WriteLine("Extracting...");
                    Directory.CreateDirectory(extractDir);
                    foreach (var e in zip2)
                    {
                        TestContext.WriteLine(" {0}", e.FileName);
                        e.Extract(extractDir);
                    }
                }

                string[] filesUnzipped = Directory.GetFiles(extractDir);
                Assert.AreEqual <int>(filesToAdd.Count, filesUnzipped.Length,
                                      "Incorrect number of files extracted.");
            }
        }
        [Timeout(5 * 60 * 1000)] // to protect against stuck file locks
        public void Spanned_WinZip_Zip_wi13691()
        {
            if (!WinZipIsPresent)
            {
                throw new Exception("WinZip is not present");
            }

            TestContext.WriteLine("Creating fodder files... {0}",
                                  DateTime.Now.ToString("G"));
            var contentDir = CreateSomeFiles();
            var filesToAdd = new List <String>(Directory.GetFiles(contentDir));

            int[] segSizes = { 128, 256, 512 };

            // Save as segmented, then read/extract with winzip unzip
            // for various segment sizes.
            for (int k = 0; k < segSizes.Length; k++)
            {
                string trialDir = String.Format("trial.{0}", k);
                Directory.CreateDirectory(trialDir);
                string nameOfParts = Path.Combine(trialDir, "InitialSave." + k);
                string zipFile1    = nameOfParts + ".zip";
                TestContext.WriteLine("");
                TestContext.WriteLine("Creating zip... T({0})...{1}",
                                      k, DateTime.Now.ToString("G"));

                // with WinZip, must produce a segmented zip in two
                // steps: first create the regular zip, then split it.

                // step 1: create the regular zip
                string args     = String.Format("-a -p -r -yx step1.zip \"{0}\"", contentDir);
                string wzzipOut = this.Exec(wzzip, args);

                // step 2: split the existing zip
                // "wzzip -ys[size] archivetosplit.zip nameofparts "
                args = String.Format("-ys{0} step1.zip {1}",
                                     segSizes[k], zipFile1        //nameOfParts
                                     );
                wzzipOut = this.Exec(wzzip, args);


                TestContext.WriteLine("");
                TestContext.WriteLine("Extracting...");
                string extractDir = Path.Combine(trialDir, "extract");
                Directory.CreateDirectory(extractDir);
                using (var zip1 = FileSystemZip.Read(zipFile1))
                {
                    foreach (var e in zip1)
                    {
                        TestContext.WriteLine(" {0}", e.FileName);
                        e.Extract(extractDir);
                    }
                }

                string[] filesUnzipped = Directory.GetFiles(extractDir);
                Assert.AreEqual <int>(filesToAdd.Count, filesUnzipped.Length,
                                      "Incorrect number of files extracted, trail {0}", k);
            }
        }
        public void UnicodeUpdate_wi12744()
        {
            const string specialEntryName = "Привет.txt";

            // two passes: one that uses the old "useUnicodeAsNecessary" property,
            // and the second that uses the newer property.
            for (int k = 0; k < 2; k++)
            {
                string zipFileToCreate = String.Format("UnicodeUpdate_wi12744-{0}.zip", k);

                TestContext.WriteLine("{0}", zipFileToCreate);
                TestContext.WriteLine("==== creating zip, trial {0}", k);
                using (ZipFile zip1 = new ZipFile())
                {
                    if (k == 0)
                    {
#pragma warning disable 618
                        zip1.UseUnicodeAsNecessary = true;
#pragma warning restore 618
                    }
                    else
                    {
                        zip1.AlternateEncoding      = System.Text.Encoding.UTF8;
                        zip1.AlternateEncodingUsage = ZipOption.AsNecessary;
                    }

                    zip1.AddEntry(specialEntryName, "this is the content of the added entry");
                    zip1.Save(zipFileToCreate);
                }


                TestContext.WriteLine("==== create a directory with 2 addl files in it");
                string subdir = Path.Combine(TopLevelDir, "files" + k);
                Directory.CreateDirectory(subdir);
                for (int i = 0; i < 2; i++)
                {
                    var filename = Path.Combine(subdir, "file" + i + ".txt");
                    TestUtilities.CreateAndFillFileText(filename, _rnd.Next(5000) + 2000);
                }

                TestContext.WriteLine("====  update the zip");
                using (ZipFile zip2 = FileSystemZip.Read(zipFileToCreate))
                {
                    zip2.AddDirectory(subdir);
                    zip2.Save(zipFileToCreate);
                }

                TestContext.WriteLine("==== check the original file in the zip");
                using (ZipFile zip3 = FileSystemZip.Read(zipFileToCreate))
                {
                    var e = zip3[specialEntryName];
                    Assert.IsTrue(e != null, "Entry not found");
                    Assert.IsTrue(e.FileName == specialEntryName, "name mismatch");
                }
            }
        }
Exemplo n.º 11
0
        public void Error_NonZipFile_wi11743()
        {
            // try reading an empty, extant file as a zip file
            string zipFileToRead = Path.GetTempFileName();

            _FilesToRemove.Add(zipFileToRead);
            using (ZipFile zip = FileSystemZip.Read(zipFileToRead))
            {
                zip.AddEntry("EntryName1.txt", "This is the content");
                zip.Save(zipFileToRead);
            }
        }
Exemplo n.º 12
0
        public void Password_MultipleEntriesDifferentPasswords()
        {
            string ZipFileToCreate = Path.Combine(TopLevelDir, "Password_MultipleEntriesDifferentPasswords.zip");

            Assert.IsFalse(File.Exists(ZipFileToCreate), "The temporary zip file '{0}' already exists.", ZipFileToCreate);


            Directory.SetCurrentDirectory(TopLevelDir);

            string[] filenames =
            {
                Path.Combine(SourceDir, "Tools",                                 TestUtilities.GetBinDir("Zipit"), "Zipit.exe"),
                Path.Combine(SourceDir, TestUtilities.GetBinDir("Zip.Portable"), "Zip.Portable.xml"),
            };

            string[] checksums =
            {
                TestUtilities.GetCheckSumString(filenames[0]),
                TestUtilities.GetCheckSumString(filenames[1]),
            };

            string[] passwords =
            {
                "12345678",
                "0987654321",
            };

            int j = 0;

            using (ZipFile zip = new ZipFile())
            {
                for (j = 0; j < filenames.Length; j++)
                {
                    zip.Password = passwords[j];
                    zip.AddFile(filenames[j], "");
                }
                zip.Save(ZipFileToCreate);
            }

            Assert.AreEqual <int>(TestUtilities.CountEntries(ZipFileToCreate), filenames.Length,
                                  "The zip file created has the wrong number of entries.");

            using (ZipFile zip = FileSystemZip.Read(ZipFileToCreate))
            {
                for (j = 0; j < filenames.Length; j++)
                {
                    zip[Path.GetFileName(filenames[j])].ExtractWithPassword("unpack", ExtractExistingFileAction.OverwriteSilently, passwords[j]);
                    string newpath = Path.Combine("unpack", filenames[j]);
                    string chk     = TestUtilities.GetCheckSumString(newpath);
                    Assert.AreEqual <string>(checksums[j], chk, "File checksums do not match.");
                }
            }
        }
Exemplo n.º 13
0
        [ExpectedException(typeof(ZipException))] // not sure which exception - could be one of several.
        public void Error_ReadCorruptedZipFile_Passwords()
        {
            string zipFileToCreate = Path.Combine(TopLevelDir, "Read_CorruptedZipFile_Passwords.zip");

            Directory.SetCurrentDirectory(TopLevelDir);

            // the list of filenames to add to the zip
            string[] filenames =
            {
                Path.Combine(SourceDir, "Tools",                                 TestUtilities.GetBinDir("Zipit"), "Zipit.exe"),
                Path.Combine(SourceDir, TestUtilities.GetBinDir("Zip.Portable"), "Zip.Portable.xml"),
                Path.Combine(SourceDir, "Tools",                                 "WinFormsApp",                    "Icon2.res"),
            };

            // passwords to use for those entries
            string[] passwords = { "12345678", "0987654321", };

            // create the zipfile, adding the files
            int j = 0;

            using (ZipFile zip = new ZipFile())
            {
                for (j = 0; j < filenames.Length; j++)
                {
                    zip.Password = passwords[j % passwords.Length];
                    zip.AddFile(filenames[j], "");
                }
                zip.Save(zipFileToCreate);
            }

            IntroduceCorruption(zipFileToCreate);

            try
            {
                // read the corrupted zip - this should fail in some way
                using (ZipFile zip = FileSystemZip.Read(zipFileToCreate))
                {
                    for (j = 0; j < filenames.Length; j++)
                    {
                        ZipEntry e = zip[Path.GetFileName(filenames[j])];

                        System.Console.WriteLine("name: {0}  compressed: {1} has password?: {2}",
                                                 e.FileName, e.CompressedSize, e.UsesEncryption);
                        Assert.IsTrue(e.UsesEncryption, "The entry does not use encryption");
                        e.ExtractWithPassword("unpack", passwords[j % passwords.Length]);
                    }
                }
            }
            catch (Exception exc1)
            {
                throw new ZipException("expected", exc1);
            }
        }
Exemplo n.º 14
0
        public void MalformedZip()
        {
            string filePath = Path.GetTempFileName();

            _FilesToRemove.Add(filePath);
            File.WriteAllText(filePath, "asdfasdf");
            string outputDirectory = Path.GetTempPath();

            using (ZipFile zipFile = FileSystemZip.Read(filePath))
            {
                zipFile.ExtractAll(outputDirectory);
            }
        }
Exemplo n.º 15
0
        internal string BasicVerifyZip(string zipfile, string password, bool emitOutput,
                                       EventHandler <ExtractProgressEventArgs> extractProgress)
        {
            // basic verification of the zip file - can it be extracted?
            // The extraction tool will verify checksums and passwords, as appropriate
#if NOT
            if (WinZipIsPresent)
            {
                TestContext.WriteLine("Verifying zip file {0} with WinZip", zipfile);
                string args = (password == null)
                    ? String.Format("-t {0}", zipfile)
                    : String.Format("-s{0} -t {1}", password, zipfile);

                string wzunzipOut = this.Exec(wzunzip, args, true, emitOutput);
            }
            else
#endif
            {
                TestContext.WriteLine("Verifying zip file {0} with DotNetZip", zipfile);
                ReadOptions options = new ReadOptions();
                if (emitOutput)
                {
                    options.StatusMessageWriter = new StringWriter();
                }

                string extractDir = "verify";
                int    c          = 0;
                while (Directory.Exists(extractDir + c))
                {
                    c++;
                }
                extractDir += c;

                using (ZipFile zip2 = FileSystemZip.Read(zipfile, options))
                {
                    zip2.Password = password;
                    if (extractProgress != null)
                    {
                        zip2.ExtractProgress += extractProgress;
                    }
                    zip2.ExtractAll(extractDir);
                }
                // emit output, as desired
                if (emitOutput)
                {
                    TestContext.WriteLine("{0}", options.StatusMessageWriter.ToString());
                }

                return(extractDir);
            }
        }
Exemplo n.º 16
0
        public void Error_Read_InvalidZip()
        {
            string filename = zipit;

            // try reading the invalid zipfile - this must fail.
            using (ZipFile zip = FileSystemZip.Read(filename))
            {
                foreach (ZipEntry e in zip)
                {
                    System.Console.WriteLine("name: {0}  compressed: {1} has password?: {2}",
                                             e.FileName, e.CompressedSize, e.UsesEncryption);
                }
            }
        }
        [Timeout(5 * 60 * 1000)] // to protect against stuck file locks
        public void Spanned_InfoZip_Zip_wi13691()
        {
            if (!InfoZipIsPresent)
            {
                throw new Exception("InfoZip is not present");
            }

            TestContext.WriteLine("Creating fodder files... {0}",
                                  DateTime.Now.ToString("G"));
            var contentDir = CreateSomeFiles();
            var filesToAdd = new List <String>(Directory.GetFiles(contentDir));

            int[] segSizes = { 128, 256, 512 };

            // Save as segmented, then read/extract with winzip unzip
            // for various segment sizes.
            for (int k = 0; k < segSizes.Length; k++)
            {
                string trialDir = String.Format("trial.{0}", k);
                Directory.CreateDirectory(trialDir);
                string zipFile1 = Path.Combine(trialDir, "InitialSave." + k + ".zip");
                TestContext.WriteLine("");
                TestContext.WriteLine("Creating zip... T({0})...{1}",
                                      k, DateTime.Now.ToString("G"));

                string args = String.Format("-s {0}k {1} -r \"{2}\"",
                                            segSizes[k],
                                            zipFile1,
                                            contentDir);
                this.Exec(infoZip, args);

                TestContext.WriteLine("");
                TestContext.WriteLine("Extracting...");
                string extractDir = Path.Combine(trialDir, "extract");
                Directory.CreateDirectory(extractDir);
                using (var zip1 = FileSystemZip.Read(zipFile1))
                {
                    foreach (var e in zip1)
                    {
                        TestContext.WriteLine(" {0}", e.FileName);
                        e.Extract(extractDir);
                    }
                }

                string[] filesUnzipped =
                    Directory.GetFiles(Path.Combine(extractDir, contentDir));
                Assert.AreEqual <int>(filesToAdd.Count, filesUnzipped.Length,
                                      "Incorrect number of files extracted, trail {0}", k);
            }
        }
Exemplo n.º 18
0
        public void Error_FileNotAvailableFails()
        {
            // verify the correct exception is being thrown
            string zipFileToCreate = Path.Combine(TopLevelDir, "Error_FileNotAvailableFails.zip");

            // create a zip file with no entries
            using (var zipfile = new ZipFile()) { zipfile.Save(zipFileToCreate); }

            // open and lock
            using (new FileStream(zipFileToCreate, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
            {
                using (FileSystemZip.Read(zipFileToCreate)) { }
            }
        }
Exemplo n.º 19
0
        [ExpectedException(typeof(ZipException))] // not sure which exception - could be one of several.
        public void Error_ReadCorruptedZipFile()
        {
            int    i;
            string zipFileToCreate = Path.Combine(TopLevelDir, "Read_CorruptedZipFile.zip");


            Directory.SetCurrentDirectory(TopLevelDir);

            // the list of filenames to add to the zip
            string[] filenames =
            {
                Path.Combine(SourceDir, "Tools",                                 TestUtilities.GetBinDir("Zipit"), "Zipit.exe"),
                Path.Combine(SourceDir, "Tools",                                 TestUtilities.GetBinDir("Unzip"), "Unzip.exe"),
                Path.Combine(SourceDir, TestUtilities.GetBinDir("Zip.Portable"), "Zip.Portable.xml"),
                Path.Combine(SourceDir, "Tools",                                 "WinFormsApp",                    "Icon2.res"),
            };

            // create the zipfile, adding the files
            using (ZipFile zip = new ZipFile())
            {
                for (i = 0; i < filenames.Length; i++)
                {
                    zip.AddFile(filenames[i], "");
                }
                zip.Save(zipFileToCreate);
            }

            // now corrupt the zip archive
            IntroduceCorruption(zipFileToCreate);

            try
            {
                // read the corrupted zip - this should fail in some way
                using (ZipFile zip = FileSystemZip.Read(zipFileToCreate))
                {
                    foreach (var e in zip)
                    {
                        System.Console.WriteLine("name: {0}  compressed: {1} has password?: {2}",
                                                 e.FileName, e.CompressedSize, e.UsesEncryption);
                        e.Extract("extract");
                    }
                }
            }
            catch (Exception exc1)
            {
                throw new ZipException("expected", exc1);
            }
        }
Exemplo n.º 20
0
        internal static int CountEntries(string zipfile)
        {
            int entries = 0;

            using (ZipFile zip = FileSystemZip.Read(zipfile))
            {
                foreach (ZipEntry e in zip)
                {
                    if (!e.IsDirectory)
                    {
                        entries++;
                    }
                }
            }
            return(entries);
        }
Exemplo n.º 21
0
        private void _Internal_ExtractExisting(int flavor)
        {
            string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("Error-Extract-ExistingFileWithoutOverwrite-{0}.zip", flavor));

            string resourceDir = Path.Combine(SourceDir, TestUtilities.GetBinDir("Zip.Portable.Tests"), "Resources");

            Assert.IsTrue(Directory.Exists(resourceDir));

            Directory.SetCurrentDirectory(TopLevelDir);
            var filenames = Directory.GetFiles(resourceDir);

            using (ZipFile zip = new ZipFile())
            {
                zip.AddFiles(filenames, "");
                zip.Comment = "This is a Comment On the Archive";
                zip.Save(zipFileToCreate);
            }

            Assert.AreEqual <int>(TestUtilities.CountEntries(zipFileToCreate), filenames.Length,
                                  "The zip file created has the wrong number of entries.");

            // Extract twice: the first time should succeed.
            // The second, should fail, because of a failed file overwrite.
            // Unless flavor==3, in which case we overwrite silently.
            for (int k = 0; k < 2; k++)
            {
                using (ZipFile zip = FileSystemZip.Read(zipFileToCreate))
                {
                    if (flavor > 10)
                    {
                        zip.ExtractProgress += OverwriteDecider;
                    }
                    for (int j = 0; j < filenames.Length; j++)
                    {
                        ZipEntry e = zip[Path.GetFileName(filenames[j])];
                        if (flavor == 4)
                        {
                            e.Extract("unpack");
                        }
                        else
                        {
                            e.Extract("unpack", (ExtractExistingFileAction)flavor);
                        }
                    }
                }
            }
        }
Exemplo n.º 22
0
        public void Error_EmptySplitZip()
        {
            string zipFileToCreate = "zftc.zip";

            using (var zip = new ZipFile())
            {
                zip.MaxOutputSegmentSize = 1024 * 1024;
                zip.Save(zipFileToCreate);
            }

            string extractDir = "extract";

            using (var zip = FileSystemZip.Read(zipFileToCreate))
            {
                zip.ExtractAll(extractDir);
                Assert.IsTrue(zip.Entries.Count == 0);
            }
        }
        public void WZA_MacCheck_ZeroLengthEntry_wi13892()
        {
            if (!WinZipIsPresent)
            {
                throw new Exception("no winzip!");
            }

            // This zipfile has some zero-length entries. Previously
            // DotNetZip was throwing a spurious MAC mismatch error on
            // those zero-length entries.
            string baseFileName = "wi13892.zip";
            string extractDir   = "extract";
            string password     = "******";

            string sourceDir = CurrentDir;

            for (int i = 0; i < 3; i++)
            {
                sourceDir = Path.GetDirectoryName(sourceDir);
            }

            string fqFileName = Path.Combine(Path.Combine(sourceDir,
                                                          "Zip Tests\\bin\\Debug\\zips"),
                                             baseFileName);

            TestContext.WriteLine("Reading zip file: '{0}'", fqFileName);
            using (ZipFile zip = FileSystemZip.Read(fqFileName))
            {
                zip.Password = password;
                foreach (ZipEntry e in zip)
                {
                    TestContext.WriteLine("{1,-22} {2,9} {3,5:F0}%   {4,9}  {5,3} {6:X8} {0}",
                                          e.FileName,
                                          e.LastModified.ToString("yyyy-MM-dd HH:mm:ss"),
                                          e.UncompressedSize,
                                          e.CompressionRatio,
                                          e.CompressedSize,
                                          (e.UsesEncryption) ? "Y" : "N",
                                          e.Crc);
                    e.Extract(extractDir);
                }
            }
        }
Exemplo n.º 24
0
        public void Password_Extract_WrongPassword()
        {
            string ZipFileToCreate = Path.Combine(TopLevelDir, "MultipleEntriesDifferentPasswords.zip");

            Assert.IsFalse(File.Exists(ZipFileToCreate), "The temporary zip file '{0}' already exists.", ZipFileToCreate);


            Directory.SetCurrentDirectory(TopLevelDir);

            string[] filenames =
            {
                Path.Combine(SourceDir, "Tools",                                 TestUtilities.GetBinDir("Zipit"), "Zipit.exe"),
                Path.Combine(SourceDir, TestUtilities.GetBinDir("Zip.Portable"), "Zip.Portable.xml"),
            };

            string[] passwords =
            {
                "12345678",
                "0987654321",
            };

            int j = 0;

            using (ZipFile zip = new ZipFile())
            {
                for (j = 0; j < filenames.Length; j++)
                {
                    zip.Password = passwords[j];
                    zip.AddFile(filenames[j], "");
                }
                zip.Save(ZipFileToCreate);
            }

            // now try to extract
            using (ZipFile zip = FileSystemZip.Read(ZipFileToCreate))
            {
                for (j = 0; j < filenames.Length; j++)
                {
                    zip[Path.GetFileName(filenames[j])].ExtractWithPassword("unpack", ExtractExistingFileAction.OverwriteSilently, "WrongPassword");
                }
            }
        }
Exemplo n.º 25
0
        public void Error_AddFile_Twice()
        {
            int i;
            // select the name of the zip file
            string zipFileToCreate = Path.Combine(TopLevelDir, "Error_AddFile_Twice.zip");

            // create the subdirectory
            string subdir = Path.Combine(TopLevelDir, "files");

            Directory.CreateDirectory(subdir);

            // create a bunch of files
            int numFilesToCreate = _rnd.Next(23) + 14;

            for (i = 0; i < numFilesToCreate; i++)
            {
                TestUtilities.CreateUniqueFile("bin", subdir, _rnd.Next(10000) + 5000);
            }

            // Create the zip archive
            Directory.SetCurrentDirectory(TopLevelDir);
            using (ZipFile zip1 = new ZipFile())
            {
                zip1.StatusMessageTextWriter = System.Console.Out;
                string[] files = Directory.GetFiles(subdir);
                zip1.AddFiles(files, "files");
                zip1.Save(zipFileToCreate);
            }


            // this should fail - adding the same file twice
            using (ZipFile zip2 = FileSystemZip.Read(zipFileToCreate))
            {
                zip2.StatusMessageTextWriter = System.Console.Out;
                string[] files = Directory.GetFiles(subdir);
                for (i = 0; i < files.Length; i++)
                {
                    zip2.AddFile(files[i], "files");
                }
                zip2.Save(zipFileToCreate);
            }
        }
Exemplo n.º 26
0
        public void Password_CheckBadPassword_wi13668()
        {
            TestContext.WriteLine("Password_CheckBadPassword_wi13668()");
            // In this case, the password is "correct" but the decrypted
            // header does not match the CRC. Therefore the library
            // should fail this password.  I don't know how the zip was
            // constructed but I suspect a broken library.
            string fileName = _GetNameForZipContentFile("wi13668-bad-pwd-472713.zip");
            string password = "******";

            TestContext.WriteLine("Reading zip file: '{0}'", fileName);
            using (ZipFile zip = FileSystemZip.Read(fileName))
            {
                foreach (ZipEntry e in zip)
                {
                    // will throw if wrong password
                    e.ExtractWithPassword(Stream.Null, password);
                }
            }
        }
Exemplo n.º 27
0
        public void Error_UseZipEntryExtractWith_ZIS_wi10355()
        {
            string zipFileToCreate = "UseOpenReaderWith_ZIS.zip";

            CreateSmallZip(zipFileToCreate);

            // mixing ZipEntry.Extract and ZipInputStream is a no-no!!

            string extractDir = "extract";

            // Use ZipEntry.Extract with ZipInputStream.
            // This must fail.
            TestContext.WriteLine("Reading with ZipInputStream");
            using (var zip = FileSystemZip.CreateInputStream(zipFileToCreate))
            {
                ZipEntry entry;
                while ((entry = zip.GetNextEntry()) != null)
                {
                    entry.Extract(extractDir, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                }
            }
        }
Exemplo n.º 28
0
        public void SilentDeletion_wi10639()
        {
            string zipFileToCreate = "SilentDeletion.zip";
            string dirToZip        = "dirToZip";
            string extractDir      = "extracted";
            string password        = TestUtilities.GenerateRandomPassword();
            string wrongPassword   = "******";
            var    files           = TestUtilities.GenerateFilesFlat(dirToZip);

            TestContext.WriteLine("Creating the zip.");
            using (var zip = new ZipFile())
            {
                zip.Password = password;
                zip.AddFiles(files, dirToZip);
                zip.Save(zipFileToCreate);
            }

            TestContext.WriteLine("Extract one file with wrong password.");

            // pick a random entry to extract
            int    ix            = -1;
            string extractedFile = null;

            // perform two passes: first with correct password to extract the
            // file.  2nd with incorrect password to see if the file is
            // deleted.

            Directory.CreateDirectory(extractDir);
            for (int i = 0; i < 2; i++)
            {
                try
                {
                    using (var zip = FileSystemZip.Read(zipFileToCreate))
                    {
                        if (i == 0)
                        {
                            do
                            {
                                ix = this._rnd.Next(zip.Entries.Count);
                            }while (zip[ix].IsDirectory);
                            TestContext.WriteLine("Selected entry: {0}", zip[ix].FileName);
                            extractedFile = Path.Combine(extractDir, zip[ix].FileName.Replace('/', Path.DirectorySeparatorChar));
                            TestContext.WriteLine("name for extracted file: {0}", extractedFile);
                            Assert.IsFalse(File.Exists(extractedFile), "The file exists.");
                        }
                        TestContext.WriteLine("Cycle {0}: ExtractWithPassword()", i);
                        zip[ix].ExtractWithPassword(extractDir,
                                                    ExtractExistingFileAction.OverwriteSilently,
                                                    (i == 0)? password : wrongPassword);
                    }
                }
                catch (BadPasswordException)
                {
                    // only swallow exceptions on the first go-round
                    if (i == 0)
                    {
                        throw;
                    }
                }
                Assert.IsTrue(File.Exists(extractedFile), "Cycle {0}: The extracted file does not exist.", i);
            }
        }
Exemplo n.º 29
0
        public void Password_BasicAddAndExtract()
        {
            int i;

            string[] Passwords = { null, "Password!", TestUtilities.GenerateRandomPassword(), "A" };

            Ionic.Zlib.CompressionLevel[] compressionLevelOptions =
            {
                Ionic.Zlib.CompressionLevel.None,
                Ionic.Zlib.CompressionLevel.BestSpeed,
                Ionic.Zlib.CompressionLevel.Default,
                Ionic.Zlib.CompressionLevel.BestCompression,
            };

            for (int k = 0; k < compressionLevelOptions.Length; k++)
            {
                for (int j = 0; j < Passwords.Length; j++)
                {
                    TestContext.WriteLine("\n\n===================\nTrial ({0}) pw({1})", j, Passwords[j]);
                    string ZipFileToCreate = Path.Combine(TopLevelDir, String.Format("Password_BasicAddAndExtract-{0}-{1}.zip", k, j));
                    Assert.IsFalse(File.Exists(ZipFileToCreate), "The temporary zip file '{0}' already exists.", ZipFileToCreate);

                    Directory.SetCurrentDirectory(TopLevelDir);
                    string DirToZip = String.Format("zipthis-{0}-{1}", k, j);
                    Directory.CreateDirectory(DirToZip);

                    TestContext.WriteLine("\n---------------------creating files and computing checksums...");
                    int      NumFilesToCreate = _rnd.Next(10) + 10;
                    string[] filenames        = new string[NumFilesToCreate];
                    var      checksums        = new Dictionary <string, string>();
                    for (i = 0; i < NumFilesToCreate; i++)
                    {
                        filenames[i] = Path.Combine(DirToZip, String.Format("file{0:D3}.txt", i));
                        int sz = _rnd.Next(22000) + 3000;
                        //int sz = 1000;
                        var repeatedLine = String.Format("Line to Repeat... {0} {1} {2} filename: {3}", i, k, j, filenames[i]);
                        TestUtilities.CreateAndFillFileText(filenames[i], repeatedLine, sz);
                        string key = Path.GetFileName(filenames[i]);
                        checksums.Add(key, TestUtilities.GetCheckSumString(filenames[i]));
                        TestContext.WriteLine("  chk[{0}]={1}", key, checksums[key]);
                    }

                    TestContext.WriteLine("\n---------------------adding files to the archive...");

                    var sw = new StringWriter();
                    using (ZipFile zip = new ZipFile())
                    {
                        zip.StatusMessageTextWriter = sw;
                        zip.CompressionLevel        = compressionLevelOptions[k];
                        zip.Password = Passwords[j];
                        zip.AddDirectory(Path.GetFileName(DirToZip));
                        zip.Save(ZipFileToCreate);
                    }
                    TestContext.WriteLine(sw.ToString());

                    Assert.AreEqual <int>(TestUtilities.CountEntries(ZipFileToCreate), NumFilesToCreate,
                                          "The Zip file has an unexpected number of entries.");

                    TestContext.WriteLine("\n---------------------verifying checksums...");

                    using (ZipFile zip = FileSystemZip.Read(ZipFileToCreate))
                    {
                        foreach (ZipEntry e in zip)
                        {
                            TestContext.WriteLine("found entry: {0}", e.FileName);
                        }

                        var extractDir = String.Format("extract-{0}-{1}", k, j);
                        TestContext.WriteLine("  Extract with pw({0})", Passwords[j]);
                        foreach (ZipEntry e in zip)
                        {
                            e.ExtractWithPassword(extractDir, ExtractExistingFileAction.OverwriteSilently, Passwords[j]);
                            if (!e.IsDirectory)
                            {
                                byte[] c2 = TestUtilities.ComputeChecksum(Path.Combine(extractDir, e.FileName));
                                Assert.AreEqual <string>(checksums[e.FileName],
                                                         TestUtilities.CheckSumToString(c2), "The checksum of the extracted file is incorrect.");
                            }
                        }
                    }
                    TestContext.WriteLine("\n");
                }
            }
        }
Exemplo n.º 30
0
        public void Password_AddEntryWithPasswordToExistingZip()
        {
            string zipFileToCreate = "AddEntryWithPasswordToExistingZip.zip";

            string[] filenames =
            {
                Path.Combine(SourceDir, "Tools",                                 TestUtilities.GetBinDir("Zipit"), "Zipit.exe"),
                Path.Combine(SourceDir, TestUtilities.GetBinDir("Zip.Portable"), "Zip.Portable.xml"),
            };

            string[] checksums =
            {
                TestUtilities.GetCheckSumString(filenames[0]),
                TestUtilities.GetCheckSumString(filenames[1]),
            };

            int j = 0;

            using (ZipFile zip = new ZipFile())
            {
                for (j = 0; j < filenames.Length; j++)
                {
                    zip.AddFile(filenames[j], "");
                }
                zip.Save(zipFileToCreate);
            }

            Assert.AreEqual <int>(TestUtilities.CountEntries(zipFileToCreate), 2,
                                  "wrong number of entries.");

            string fileX     = Path.Combine(SourceDir, "Tools", TestUtilities.GetBinDir("Unzip"), "unzip.exe");
            string checksumX = TestUtilities.GetCheckSumString(fileX);
            string password  = TestUtilities.GenerateRandomPassword() + "!";

            using (ZipFile zip = FileSystemZip.Read(zipFileToCreate))
            {
                zip.Password = password;
                zip.AddFile(fileX, "");
                zip.Save(zipFileToCreate);
            }

            Assert.AreEqual <int>(TestUtilities.CountEntries(zipFileToCreate), 3,
                                  "wrong number of entries.");

            string unpackDir = "unpack";
            string newpath, chk, baseName;

            using (ZipFile zip = FileSystemZip.Read(zipFileToCreate))
            {
                for (j = 0; j < filenames.Length; j++)
                {
                    baseName = Path.GetFileName(filenames[j]);
                    zip[baseName].Extract(unpackDir, ExtractExistingFileAction.OverwriteSilently);
                    newpath = Path.Combine(unpackDir, filenames[j]);
                    chk     = TestUtilities.GetCheckSumString(newpath);
                    Assert.AreEqual <string>(checksums[j], chk, "Checksums do not match.");
                }

                baseName = Path.GetFileName(fileX);

                zip[baseName].ExtractWithPassword(unpackDir,
                                                  ExtractExistingFileAction.OverwriteSilently,
                                                  password);

                newpath = Path.Combine(unpackDir, fileX);
                chk     = TestUtilities.GetCheckSumString(newpath);
                Assert.AreEqual <string>(checksumX, chk, "Checksums do not match.");
            }
        }