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 new ZipInputStream(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);
                }
            }
        }
        public void Password_BasicAddAndExtract()
        {
            int i;
            string[] Passwords = { null, "Password!", TestUtilities.GenerateRandomPassword(), "A" };

            Alienlab.Zlib.CompressionLevel[] compressionLevelOptions = {
                Alienlab.Zlib.CompressionLevel.None,
                Alienlab.Zlib.CompressionLevel.BestSpeed,
                Alienlab.Zlib.CompressionLevel.Default,
                Alienlab.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(ZipFileToCreate, sw))
                    {
                        zip.CompressionLevel = compressionLevelOptions[k];
                        zip.Password = Passwords[j];
                        zip.AddDirectory(Path.GetFileName(DirToZip));
                        zip.Save();
                    }
                    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 = ZipFile.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");
                }
            }
        }
        public void UpdateZip_AddNewDirectory()
        {
            string zipFileToCreate = Path.Combine(TopLevelDir, "UpdateZip_AddNewDirectory.zip");

            String CommentOnArchive = "BasicTests::UpdateZip_AddNewDirectory(): This archive will be overwritten.";

            string newComment = "This comment has been OVERWRITTEN." + DateTime.Now.ToString("G");
            string dirToZip = Path.Combine(TopLevelDir, "zipup");

            int i, j;
            int entries = 0;
            string subdir = null;
            String filename = null;
            int subdirCount = _rnd.Next(4) + 4;
            for (i = 0; i < subdirCount; i++)
            {
                subdir = Path.Combine(dirToZip, "Directory." + i);
                Directory.CreateDirectory(subdir);

                int fileCount = _rnd.Next(3) + 3;
                for (j = 0; j < fileCount; j++)
                {
                    filename = Path.Combine(subdir, "file" + j + ".txt");
                    TestUtilities.CreateAndFillFileText(filename, _rnd.Next(12000) + 5000);
                    entries++;
                }
            }

            using (ZipFile zip = new ZipFile())
            {
                zip.AddDirectory(dirToZip);
                zip.Comment = CommentOnArchive;
                zip.Save(zipFileToCreate);
            }

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

            BasicVerifyZip(zipFileToCreate);

            // Now create a new subdirectory and add that one
            subdir = Path.Combine(TopLevelDir, "NewSubDirectory");
            Directory.CreateDirectory(subdir);

            filename = Path.Combine(subdir, "newfile.txt");
            TestUtilities.CreateAndFillFileText(filename, _rnd.Next(12000) + 5000);
            entries++;

            using (ZipFile zip = new ZipFile(zipFileToCreate))
            {
                zip.AddDirectory(subdir);
                zip.Comment = newComment;
                // this will add entries into the existing zip file
                zip.Save();
            }

            Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entries,
                    "The overwritten Zip file has the wrong number of entries.");

            using (ZipFile readzip = new ZipFile(zipFileToCreate))
            {
                Assert.AreEqual<string>(newComment,
                                        readzip.Comment,
                                        "The zip comment is incorrect.");
            }
        }
        public void ReadZip_OpenReader()
        {
            string[] passwords = { null, Path.GetRandomFileName(), "EE", "***()" };

            for (int j = 0; j < compLevels.Length; j++)
            {
                for (int k = 0; k < passwords.Length; k++)
                {
                    string zipFileToCreate = String.Format("ReadZip_OpenReader-{0}-{1}.zip", j, k);
                    //int entriesAdded = 0;
                    //String filename = null;
                    string dirToZip = String.Format("dirToZip.{0}.{1}", j, k);
                    var files = TestUtilities.GenerateFilesFlat(dirToZip);

                    using (ZipFile zip1 = new ZipFile())
                    {
                        zip1.CompressionLevel = compLevels[j];
                        zip1.Password = passwords[k];
                        zip1.AddDirectory(dirToZip,dirToZip);
                        zip1.Save(zipFileToCreate);
                    }

                    // Verify the files are in the zip
                    Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate),
                                         files.Length,
                                         String.Format("Trial ({0},{1})", j, k));

                    int i = 0;
                    ZipEntry e1 = null;
                    Func<Ionic.Crc.CrcCalculatorStream> opener = () => {
                        if (i == 0)
                            return e1.OpenReader();
                        if (i == 1)
                            return e1.OpenReader(passwords[k]);

                        e1.Password = passwords[k];
                        return e1.OpenReader();
                    };

                    // now extract the files and verify their contents
                    using (ZipFile zip2 = ZipFile.Read(zipFileToCreate))
                    {
                        for (i = 0; i < 3; i++)
                        {
                            // try once with Password set on ZipFile,
                            // another with password on the entry, and
                            // a third time with password passed into the OpenReader() method.
                            if (i == 0) zip2.Password = passwords[k];

                            foreach (string eName in zip2.EntryFileNames)
                            {
                                e1 = zip2[eName];
                                if (e1.IsDirectory) continue;

                                using (var s = opener())
                                {
                                    string outFile = String.Format("{0}.{1}.out", eName, i);
                                    int totalBytesRead = 0;
                                    using (var output = File.Create(outFile))
                                    {
                                        byte[] buffer = new byte[4096];
                                        int n;
                                        while ((n = s.Read(buffer, 0, buffer.Length)) > 0)
                                        {
                                            totalBytesRead += n;
                                            output.Write(buffer, 0, n);
                                        }
                                    }

                                    TestContext.WriteLine("CRC expected({0:X8}) actual({1:X8})",
                                                          e1.Crc, s.Crc);
                                    Assert.AreEqual<Int32>(s.Crc, e1.Crc,
                                                           string.Format("{0} :: CRC Mismatch", eName));
                                    Assert.AreEqual<Int32>(totalBytesRead, (int)e1.UncompressedSize,
                                                           string.Format("We read an unexpected number of bytes. ({0})", eName));
                                }
                            }
                        }
                    }
                }
            }
        }
        public void CreateZip_AddDirectory_LargeNumberOfSmallFiles()
        {
            // start the visible progress monitor
            _txrx = TestUtilities.StartProgressMonitor("LargeNumberOfSmallFiles",
                                                       "Large # of Small Files",
                                                       "Creating files");
            int max1 = 0;
            Action<Int16, Int32> progressUpdate = (x, y) => {
                if (x == 0)
                {
                    _txrx.Send(String.Format("pb 1 max {0}", y));
                    max1 = y;
                }
                else if (x == 2)
                {
                    _txrx.Send(String.Format("pb 1 value {0}", y));
                    _txrx.Send(String.Format("status creating directory {0} of {1}",
                                             y, max1));
                }
                else if (x == 4)
                {
                    _txrx.Send(String.Format("status done creating {0} files", y));
                }
            };

            int[][] settings = {
                // sizes and numbers of files/directories to create
                new int[] {71, 21, 97, 27, 200, 200 },
                new int[] {51, 171, 47, 197, 100, 100 },
            };
            _txrx.Send(String.Format("pb 0 max {0}", settings.Length * 2));
            TestContext.WriteLine("============================================");
            TestContext.WriteLine("Test beginning - {0}", DateTime.Now.ToString("G"));
            for (int m = 0; m < settings.Length; m++)
            {
                string zipFileToCreate = String.Format("LrgNumOfSmallFiles-{0}.zip", m);
                string dirToZip =  "zipthis" + m;
                Directory.CreateDirectory(dirToZip);
                TestContext.WriteLine("============================================");
                TestContext.WriteLine("Creating files, cycle {0}...", m);

                int subdirCount = 0;
                int entries =
                    TestUtilities.GenerateFilesOneLevelDeep(TestContext,
                                                            "LargeNumberOfFiles",
                                                            dirToZip,
                                                            settings[m],
                                                            progressUpdate,
                                                            out subdirCount);
                _numEntriesToAdd = entries;  // used in LNSF_AddProgress
                _numEntriesAdded = 0;

                _txrx.Send("pb 0 step");
                TestContext.WriteLine("============================================");
                TestContext.WriteLine("Total of {0} files in {1} subdirs",
                                      entries, subdirCount);
                TestContext.WriteLine("Creating zip - {0}", DateTime.Now.ToString("G"));
                Directory.SetCurrentDirectory(TopLevelDir);
                _pb1Set = false;
                using (ZipFile zip = new ZipFile())
                {
                    zip.AddProgress += LNSF_AddProgress;
                    zip.AddDirectory(Path.GetFileName(dirToZip));
                    _txrx.Send("test Large # of Small Files"); // for good measure
                    zip.BufferSize = 4096;
                    zip.SortEntriesBeforeSaving = true;
                    zip.SaveProgress += LNSF_SaveProgress;
                    zip.Save(zipFileToCreate);
                }

                _txrx.Send("pb 0 step");

                TestContext.WriteLine("Checking zip - {0}", DateTime.Now.ToString("G"));
                Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entries);

                _txrx.Send("status cleaning up...");
                // clean up for this cycle
                Directory.Delete(dirToZip, true);
            }
            TestContext.WriteLine("============================================");
            TestContext.WriteLine("Test end - {0}", DateTime.Now.ToString("G"));
        }
        public void LargeFile_WithProgress()
        {
            // This test checks the Int64 limits in progress events (Save + Extract)
            TestContext.WriteLine("Test beginning {0}", System.DateTime.Now.ToString("G"));

            _txrx = TestUtilities.StartProgressMonitor("LargeFile_WithProgress",
                                                       "Large File Save and Extract",
                                                       "Creating a large file...");

            _txrx.Send("bars 3");
            System.Threading.Thread.Sleep(120);
            _txrx.Send("pb 0 max 3");

            string zipFileToCreate = "LargeFile_WithProgress.zip";
            string unpackDir = "unpack";
            string dirToZip = "LargeFile";
            string baseName = "LargeFile.bin";
            Directory.CreateDirectory(dirToZip);

            Int64 minFileSize = 0x7FFFFFFFL + _rnd.Next(1000000);
            TestContext.WriteLine("Creating a large file, size>={0}", minFileSize);
            string filename = Path.Combine(dirToZip, baseName);
            _txrx.Send(String.Format("pb 1 max {0}", minFileSize));

            Action<Int64> progressUpdate = (x) =>
                {
                    _txrx.Send(String.Format("pb 1 value {0}", x));
                    _txrx.Send(String.Format("status Creating a large file, ({0}/{1}mb) ({2:N0}%)",
                                             x / (1024 * 1024), minFileSize / (1024 * 1024),
                                             ((double)x) / (0.01 * minFileSize)));
                };

            // this will take about a minute
            TestUtilities.CreateAndFillFileBinaryZeroes(filename, minFileSize, progressUpdate);

            InjectNoise(filename);

            _txrx.Send("pb 0 step");
            var finfo = new FileInfo(filename);
            var actualFileSize = finfo.Length;

            TestContext.WriteLine("File Create complete {0}", System.DateTime.Now.ToString("G"));

            maxBytesXferred = 0;
            using (ZipFile zip1 = new ZipFile())
            {
                zip1.SaveProgress += LF_SaveProgress;
                zip1.Comment = "This is the comment on the zip archive.";
                zip1.AddEntry("Readme.txt", "This is some content.");
                zip1.AddDirectory(dirToZip, dirToZip);
                zip1.BufferSize = 65536 * 8;      // 512k
                zip1.CodecBufferSize = 65536 * 2; // 128k
                zip1.Save(zipFileToCreate);
            }

            _txrx.Send("pb 0 step");
            TestContext.WriteLine("Save complete {0}", System.DateTime.Now.ToString("G"));
            Assert.AreEqual<Int64>(actualFileSize, maxBytesXferred);
            var chk1 = TestUtilities.ComputeChecksum(filename);

            // remove the large file before extracting
            Directory.Delete(dirToZip, true);

            _pb1Set = _pb2Set = false;
            maxBytesXferred = 0;
            using (ZipFile zip2 = ZipFile.Read(zipFileToCreate))
            {
                _numFilesToExtract = zip2.Entries.Count;
                zip2.ExtractProgress += LF_ExtractProgress;
                zip2.BufferSize = 65536 * 8;
                zip2.ExtractAll(unpackDir);
            }

            _txrx.Send("pb 0 step");

            TestContext.WriteLine("Extract complete {0}", System.DateTime.Now.ToString("G"));
            Assert.AreEqual<Int64>(actualFileSize, maxBytesXferred);
            var exFile = Path.Combine(unpackDir, Path.Combine(dirToZip, baseName));
            var chk2 = TestUtilities.ComputeChecksum(exFile);

            string s1 = TestUtilities.CheckSumToString(chk1);
            string s2 = TestUtilities.CheckSumToString(chk2);
            Assert.AreEqual<string>(s1,s2);
            TestContext.WriteLine("     Checksums match ({0}).\n", s2);
            TestContext.WriteLine("Test complete {0}", System.DateTime.Now.ToString("G"));
        }
        public void TestZip_IsZipFile_Stream()
        {
            string zipFileToCreate = Path.Combine(TopLevelDir, "TestZip_IsZipFile_Stream.zip");
            int entriesAdded = 0;
            String filename = null;
            string subdir = Path.Combine(TopLevelDir, "A");
            Directory.CreateDirectory(subdir);

            int fileCount = _rnd.Next(10) + 10;
            for (int j = 0; j < fileCount; j++)
            {
                filename = Path.Combine(subdir, String.Format("FileToBeAdded-{0:D2}.txt", j));
                TestUtilities.CreateAndFillFileText(filename, _rnd.Next(34000) + 5000);
                entriesAdded++;
            }

            using (ZipFile zip1 = new ZipFile())
            {
                zip1.AddDirectory(subdir, Path.GetFileName(subdir));
                zip1.Save(zipFileToCreate);
            }

            // Verify the files are in the zip
            Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesAdded,
                                 "The Zip file has the wrong number of entries.");

            using (FileStream input = File.OpenRead(zipFileToCreate))
            {
                Assert.IsTrue(ZipFile.IsZipFile(input, false),
                              "The IsZipFile() method returned an unexpected result for an existing zip file.");
            }

            using (FileStream input = File.OpenRead(zipFileToCreate))
            {
                Assert.IsTrue(ZipFile.IsZipFile(input, true),
                              "The IsZipFile() method returned an unexpected result for an existing zip file.");
            }
        }
        public void Create_WithEvents()
        {
            string dirToZip = Path.Combine(TopLevelDir, "EventTest");
            Directory.CreateDirectory(dirToZip);

            var randomizerSettings = new int[]
                {
                    6, 4,        // dircount
                    7, 8,        // filecount
                    10000, 15000 // filesize
                };
            int subdirCount = 0;
            int entriesAdded = TestUtilities.GenerateFilesOneLevelDeep(TestContext, "Create_WithEvents", dirToZip, randomizerSettings, null, out subdirCount);

            for (int m = 0; m < 2; m++)
            {
                TestContext.WriteLine("=======================================================");
                TestContext.WriteLine("Trial {0}", m);

                string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("Create_WithEvents-{0}.zip", m));
                string targetDirectory = Path.Combine(TopLevelDir, "unpack" + m.ToString());

                _progressEventCalls = 0;
                _cancelIndex = -1; // don't cancel this Save

                // create a zip file
                using (ZipFile zip1 = new ZipFile())
                {
                    zip1.SaveProgress += SaveProgress;
                    zip1.Comment = "This is the comment on the zip archive.";
                    zip1.AddDirectory(dirToZip, Path.GetFileName(dirToZip));
                    zip1.Save(zipFileToCreate);
                }

                if (m > 0)
                {
                    // update the zip file
                    using (ZipFile zip1 = ZipFile.Read(zipFileToCreate))
                    {
                        zip1.SaveProgress += SaveProgress;
                        zip1.Comment = "This is the comment on the zip archive.";
                        zip1.AddEntry("ReadThis.txt", "This is the content for the readme file in the archive.");
                        zip1.Save();
                    }
                    entriesAdded++;
                }

                int expectedNumberOfProgressCalls = (entriesAdded + subdirCount) * (m + 1) + 1;
                Assert.AreEqual<Int32>(expectedNumberOfProgressCalls, _progressEventCalls,
                                       "The number of progress events was unexpected ({0}!={1}).", expectedNumberOfProgressCalls, _progressEventCalls);

                _progressEventCalls = 0;
                _cancelIndex = -1; // don't cancel this Extract
                using (ZipFile zip2 = ZipFile.Read(zipFileToCreate))
                {
                    zip2.ExtractProgress += ExtractProgress;
                    zip2.ExtractAll(targetDirectory);
                }

                Assert.AreEqual<Int32>(_progressEventCalls, entriesAdded + subdirCount + 1,
                                       "The number of Entries added is not equal to the number of entries extracted.");

            }

        }
        public void _Internal_DuplicateNames_DifferentFolders_wi8982(bool flat)
        {
            Directory.SetCurrentDirectory(TopLevelDir);
            string dirToZip = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
            TestUtilities.GenerateFilesFlat(dirToZip, 3);
            string subdir = Path.Combine(dirToZip, "subdir1");
            TestUtilities.GenerateFilesFlat(subdir, 2);

            for (int i = 0; i < 2; i++)
            {
                string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("Create_DuplicateNames_DifferentFolders.{0}.zip", i));

                using (var zip = new ZipFile())
                {
                    zip.ZipErrorAction = ZipErrorAction.Throw;
                    if (i == 0)
                        zip.AddDirectory(dirToZip, "fodder");
                    else
                    {
                        var files = Directory.GetFiles(dirToZip, "*.*", SearchOption.AllDirectories);
                        if (flat)
                            zip.AddFiles(files, "fodder");
                        else
                            zip.AddFiles(files, true, "fodder");

                    }

                    zip.Save(zipFileToCreate);
                }

                BasicVerifyZip(zipFileToCreate);

                Assert.AreEqual<int>(5, TestUtilities.CountEntries(zipFileToCreate),
                                     "Trial {0}: The zip file created has the wrong number of entries.", i);
            }
        }
        private void _Internal_AddDirectory_ReparsePoint_wi8617(int flavor)
        {
            string zipFileToCreate = Path.Combine(TopLevelDir,
                                                  String.Format("AddDirectory_ReparsePoint-{0}.zip",
                                                                flavor));
            string dirToZip = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
            var files = TestUtilities.GenerateFilesFlat(dirToZip);

            string junction = Path.Combine(dirToZip, "cycle");
            Alienlab.IO.JunctionPoint.Create(junction, dirToZip);

            using (var zip = new ZipFile())
            {
                if (flavor == 1)
                    zip.AddDirectoryWillTraverseReparsePoints = false;
                else if (flavor == 2)
                    zip.AddDirectoryWillTraverseReparsePoints = true;
                // else nothing
                zip.AddDirectory(dirToZip, "fodder");
                zip.Save(zipFileToCreate);
            }

            BasicVerifyZip(zipFileToCreate);

            Assert.AreEqual<int>(files.Length, TestUtilities.CountEntries(zipFileToCreate),
                                 "The zip file created has the wrong number of entries.");
        }
        public void ExtractAll_WithPassword()
        {
            string zipFileToCreate = Path.Combine(TopLevelDir, "ExtractAll_WithPassword.zip");
            string targetDirectory = Path.Combine(TopLevelDir, "unpack");
            string dirToZip = Path.Combine(TopLevelDir, "dirToZip");
            Directory.CreateDirectory(dirToZip);
            int subdirCount = 0;

            int entriesAdded = TestUtilities.GenerateFilesOneLevelDeep(TestContext, "ExtractAll_WithPassword", dirToZip, null, out subdirCount);
            string password = TestUtilities.GenerateRandomPassword();
            using (ZipFile zip1 = new ZipFile())
            {
                zip1.Password = password;
                zip1.Comment = "Brick walls are there for a reason: to let you show how badly you want your goal.";
                zip1.AddDirectory(dirToZip, Path.GetFileName(dirToZip));
                zip1.Save(zipFileToCreate);
            }

            BasicVerifyZip(zipFileToCreate, password);

            _cancelIndex = -1; // don't cancel this Extract
            _progressEventCalls = 0;
            using (ZipFile zip2 = ZipFile.Read(zipFileToCreate))
            {
                zip2.Password = password;
                zip2.ExtractProgress += ExtractProgress;
                zip2.ExtractAll(targetDirectory);
            }

            Assert.AreEqual<Int32>(_progressEventCalls, entriesAdded + subdirCount + 1);
        }
        public void ExtractAll_Cancellation()
        {
            string zipFileToCreate = Path.Combine(TopLevelDir, "ExtractAll_Cancellation.zip");
            string targetDirectory = Path.Combine(TopLevelDir, "unpack");
            string dirToZip = Path.Combine(TopLevelDir, "EventTest");
            Directory.CreateDirectory(dirToZip);
            int subdirCount = 0;
            int entriesAdded = TestUtilities.GenerateFilesOneLevelDeep(TestContext, "ExtractAll_Cancellation", dirToZip, null, out subdirCount);

            using (ZipFile zip1 = new ZipFile())
            {
                zip1.Comment = "The extract on this zip archive will be canceled.";
                zip1.AddDirectory(dirToZip, Path.GetFileName(dirToZip));
                zip1.Save(zipFileToCreate);
            }

            BasicVerifyZip(zipFileToCreate);

            _cancelIndex = entriesAdded - _rnd.Next(entriesAdded / 2);
            _progressEventCalls = 0;
            using (ZipFile zip2 = ZipFile.Read(zipFileToCreate))
            {
                zip2.ExtractProgress += ExtractProgress;
                zip2.ExtractAll(targetDirectory);
            }

            Assert.AreEqual<Int32>(_progressEventCalls, _cancelIndex);
        }
        public void Create_AddCancellation_wi13371()
        {
            string zipFileToCreate = Path.Combine(TopLevelDir, "Create_AddCancellation.zip");

            string dirToZip = Path.Combine(TopLevelDir, "EventTest");
            Directory.CreateDirectory(dirToZip);
            int subdirCount = 0;
            int entriesAdded = TestUtilities.GenerateFilesOneLevelDeep(TestContext, "Create_AddCancellation", dirToZip, null, out subdirCount);

            _cancelIndex = entriesAdded - _rnd.Next(entriesAdded / 2);
            _progressEventCalls = 0;
            _wasCanceled = false;
            using (ZipFile zip1 = new ZipFile())
            {
                zip1.AddProgress += AddProgress;
                zip1.Comment = "The add of files into this zip archive will be canceled.";
                zip1.AddDirectory(dirToZip, Path.GetFileName(dirToZip));
                if (!_wasCanceled)
                    zip1.Save(zipFileToCreate);
            }

            Assert.AreEqual<Int32>(_progressEventCalls, _cancelIndex);

            Assert.IsFalse(File.Exists(zipFileToCreate), "The zip file should not exist.");
        }
        public void Create_AddDirectory_NoFilesInRoot_WI5893a()
        {
            string zipFileToCreate = Path.Combine(TopLevelDir, "Create_AddDirectory_NoFilesInRoot_WI5893a.zip");

            int i, j;
            int entries = 0;
            int subdirCount = _rnd.Next(4) + 4;
            for (i = 0; i < subdirCount; i++)
            {
                string subdir = Path.Combine(TopLevelDir, "DirectoryToZip.test." + i);
                Directory.CreateDirectory(subdir);

                int fileCount = _rnd.Next(16) + 8;
                for (j = 0; j < fileCount; j++)
                {
                    String file = Path.Combine(subdir, String.Format("testfile{0:D3}.a", j));
                    TestUtilities.CreateAndFillFile(file, _rnd.Next(100) + 500);
                    entries++;
                }
            }

            using (ZipFile zip = new ZipFile())
            {
                zip.AddDirectory(TopLevelDir, string.Empty);
                zip.Save(zipFileToCreate);
            }

            BasicVerifyZip(zipFileToCreate);

            Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entries, "The Zip file has the wrong number of entries.");
        }
        public void WZA_CreateZip_DirectoriesOnly()
        {
            if (!WinZipIsPresent)
                throw new Exception("no winzip! [WZA_CreateZip_DirectoriesOnly]");

            string zipFileToCreate = "WZA_CreateZip_DirectoriesOnly.zip";
            Assert.IsFalse(File.Exists(zipFileToCreate));

            string password = TestUtilities.GenerateRandomPassword();
            string dirToZip = Path.Combine(TopLevelDir, "zipthis");
            Directory.CreateDirectory(dirToZip);

            int entries = 0;
            int subdirCount = _rnd.Next(8) + 8;

            TestContext.WriteLine("Creating file   {0}", zipFileToCreate);
            TestContext.WriteLine("  Password:     {0}", password);
            TestContext.WriteLine("  #directories: {0}", subdirCount);

            for (int i = 0; i < subdirCount; i++)
            {
                string subdir = Path.Combine(dirToZip, "EmptyDir" + i);
                Directory.CreateDirectory(subdir);
            }

            using (ZipFile zip1 = new ZipFile())
            {
                zip1.Encryption = EncryptionAlgorithm.WinZipAes256;
                zip1.Password = password;
                zip1.AddDirectory(Path.GetFileName(dirToZip));
                zip1.Save(zipFileToCreate);
            }

            BasicVerifyZip(zipFileToCreate, password);

            Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entries);
        }