Exemplo n.º 1
0
        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 = ZipFile.Read(zipFileToCreate))
                {
                    zip2.AddDirectory(subdir);
                    zip2.Save();
                }

                TestContext.WriteLine("==== check the original file in the zip");
                using (ZipFile zip3 = ZipFile.Read(zipFileToCreate))
                {
                    var e = zip3[specialEntryName];
                    Assert.IsTrue(e!=null, "Entry not found");
                    Assert.IsTrue(e.FileName == specialEntryName, "name mismatch");
                }
            }
        }
        public void Test_AddEntry_String()
        {
            string[] passwords = { null, "Password", TestUtilities.GenerateRandomPassword(), "A" };

            Encoding[] encodings = { Encoding.UTF8,
                                     Encoding.Default,
                                     Encoding.ASCII,
                                     Encoding.GetEncoding("Big5"),
                                     Encoding.GetEncoding("iso-8859-1"),
                                     Encoding.GetEncoding("Windows-1252"),
                };

            string testBin = TestUtilities.GetTestBinDir(CurrentDir);
            string testStringsFile = Path.Combine(testBin, "Resources\\TestStrings.txt");
            var contentStrings = File.ReadAllLines(testStringsFile);

            int[] successfulEncodings = new int[contentStrings.Length];

            for (int a = 0; a < crypto.Length; a++)
            {
                for (int b = 0; b < passwords.Length; b++)
                {
                    for (int c = 0; c < encodings.Length; c++)
                    {
                        string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("Test_AddEntry_String-{0}.{1}.{2}.zip", a, b, c));
                        Assert.IsFalse(File.Exists(zipFileToCreate), "The zip file '{0}' already exists.", zipFileToCreate);


                        // add entries to a zipfile.
                        // use a password.(possibly null)
                        using (ZipFile zip1 = new ZipFile(zipFileToCreate))
                        {
                            zip1.Comment = String.Format("Test zip file.\nEncryption({0}) Pw({1}) fileEncoding({2})",
                                                        crypto[a].ToString(),
                                                        passwords[b],
                                                        encodings[c].ToString());
                            zip1.Encryption = crypto[a];
                            zip1.Password = passwords[b];
                            for (int d = 0; d < contentStrings.Length; d++)
                            {
                                string entryName = String.Format("File{0}.txt", d + 1);
                                // add each string using the given encoding
                                zip1.AddEntry(entryName, contentStrings[d], encodings[c]);
                            }
                            zip1.Save();
                        }

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



                        using (ZipFile zip2 = ZipFile.Read(zipFileToCreate))
                        {
                            zip2.Password = passwords[b];
                            for (int d = 0; d < contentStrings.Length; d++)
                            {
                                try
                                {
                                    string entryName = String.Format("File{0}.txt", d + 1);
                                    //zip2[entryName].Password = Passwords[b];  // should not be necessary
                                    using (Stream s = zip2[entryName].OpenReader())
                                    {
                                        using (var sr = new StreamReader(s, encodings[c]))
                                        {
                                            try
                                            {
                                                Assert.AreNotEqual<StreamReader>(null, sr);
                                                string retrievedContent = sr.ReadLine();
                                                if (IsEncodable(contentStrings[d], encodings[c]))
                                                {
                                                    Assert.AreEqual<String>(contentStrings[d], retrievedContent,
                                                                            "encryption({0}) pw({1}) encoding({2}), contentString({3}) file({4}): the content did not match.",
                                                                            a, b, c, d, entryName);
                                                    successfulEncodings[d]++;
                                                }
                                                else
                                                {
                                                    Assert.AreNotEqual<Encoding>(Encoding.UTF8, encodings[c]);
                                                    Assert.AreNotEqual<String>(contentStrings[d], retrievedContent,
                                                                               "encryption({0}) pw({1}) encoding({2}), contentString({3}) file({4}): the content should not match, but does.",
                                                                               a, b, c, d, entryName);
                                                }
                                            }
                                            catch (Exception exc1)
                                            {
                                                TestContext.WriteLine("Exception while reading: a({0}) b({1}) c({2}) d({3})",
                                                                      a, b, c, d);
                                                throw new Exception("broken", exc1);
                                            }
                                        }
                                    }

                                }
                                catch (Exception e1)
                                {
                                    TestContext.WriteLine("Exception in OpenReader: Encryption({0}) pw({1}) c({2}) d({3})",
                                                          crypto[a].ToString(),
                                                          passwords[b],
                                                          encodings[c].ToString(),
                                                          d);

                                    throw new Exception("broken", e1);
                                }
                            }
                        }
                    }
                }
            }

            for (int d = 0; d < successfulEncodings.Length; d++)
                Assert.AreNotEqual<Int32>(0, successfulEncodings[d], "Content item #{0} ({1}) was never encoded successfully.", d, contentStrings[d]);

        }
Exemplo n.º 3
0
        [TestMethod, Timeout(30 * 60 * 1000)]  // in ms.  30*60*100 == 30min
        public void ZipFile_PDOS_LeakTest_wi10030()
        {
            // Test memory growth over many many cycles.
            // There was a leak in the ParallelDeflateOutputStream, where
            // the PDOS was not being GC'd.  This test checks for that.
            //
            // If the error is present, this test will either timeout or
            // throw an InsufficientMemoryException (or whatever).  The
            // timeout occurs because GC begins to get verrrrry
            // sloooooow.  IF the error is not present, this test will
            // complete successfully, in about 20 minutes.
            //

            string zipFileToCreate = "ZipFile_PDOS_LeakTest_wi10030.zip";
            int nCycles = 4096;
            int nFiles = 3;
            int sizeBase = 384 * 1024;
            int sizeRange = 32 * 1024;
            int count = 0;
            byte[] buffer = new byte[1024];
            int n;

            // fill a couple memory streams with random text
            MemoryStream[] ms = new MemoryStream[nFiles];
            for (int i = 0; i < ms.Length; i++)
            {
                ms[i] = new MemoryStream();
                int sz = sizeBase + _rnd.Next(sizeRange);
                using (Stream rtg = new Alienlab.Zip.Tests.Utilities.RandomTextInputStream(sz))
                {
                    while ((n = rtg.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        ms[i].Write(buffer, 0, n);
                    }
                }
            }
            buffer = null;

            OpenDelegate opener = (x) =>
                {
                    Stream s = ms[count % ms.Length];
                    s.Seek(0L, SeekOrigin.Begin);
                    count++;
                    return s;
                };

            CloseDelegate closer = (e, s) =>
                {
                    //s.Close();
                };

            string txrxLabel = "PDOS Leak Test";
            _txrx = TestUtilities.StartProgressMonitor("ZipFile_PDOS_LeakTest_wi10030", txrxLabel, "starting up...");

            TestContext.WriteLine("Testing for leaks....");

            _txrx.Send(String.Format("pb 0 max {0}", nCycles));
            _txrx.Send("pb 0 value 0");

            for (int x = 0; x < nCycles; x++)
            {
                if (x != 0 && x % 16 == 0)
                {
                    TestContext.WriteLine("Cycle {0}...", x);
                    string status = String.Format("status Cycle {0}/{1} {2:N0}%",
                                                  x + 1, nCycles,
                                                  ((x+1)/(0.01 * nCycles)));
                    _txrx.Send(status);
                }

                using (ZipFile zip = new ZipFile())
                {
                    zip.ParallelDeflateThreshold = 128 * 1024;
                    zip.CompressionLevel = Alienlab.Zlib.CompressionLevel.BestCompression;
                    //zip.SaveProgress += streams_SaveProgress;
                    for (int y = 0; y < nFiles; y++)
                    {
                        zip.AddEntry("Entry" + y + ".txt", opener, closer);
                    }
                    zip.Comment = "Produced at " + System.DateTime.UtcNow.ToString("G");
                    zip.Save(zipFileToCreate);
                }

                _txrx.Send("pb 0 step");
            }

            for (int i = 0; i < ms.Length; i++)
            {
                ms[i].Dispose();
                ms[i] = null;
            }
            ms = null;
        }
Exemplo n.º 4
0
        private void _Internal_AddEntry_WriteDelegate(string[] files,
                                                      EncryptionAlgorithm crypto,
                                                      bool seekable,
                                                      int cycle,
                                                      string format,
                                                      int ignored)
        {
            int bufferSize = 2048;
            byte[] buffer = new byte[bufferSize];
            int n;

            for (int k = 0; k < compLevels.Length; k++)
            {
                string zipFileToCreate = Path.Combine(TopLevelDir, String.Format(format, compLevels[k].ToString()));
                string password = TestUtilities.GenerateRandomPassword();

                using (var zip = new ZipFile())
                {
                    TestContext.WriteLine("=================================");
                    TestContext.WriteLine("Creating {0}...", Path.GetFileName(zipFileToCreate));
                    TestContext.WriteLine("Encryption({0})  Compression({1})  pw({2})",
                                          crypto.ToString(), compLevels[k].ToString(), password);

                    zip.Password = password;
                    zip.Encryption = crypto;
                    zip.CompressionLevel = compLevels[k];

                    foreach (var file in files)
                    {
                        zip.AddEntry(file, (name, output) =>
                            {
                                using (var input = File.OpenRead(name))
                                {
                                    while ((n = input.Read(buffer, 0, buffer.Length)) != 0)
                                    {
                                        output.Write(buffer, 0, n);
                                    }
                                }
                            });
                    }


                    if (!seekable)
                    {
                        // conditionally use a non-seekable output stream
                        using (var raw = File.Create(zipFileToCreate))
                        {
                            using (var ns = new Alienlab.Zip.Tests.NonSeekableOutputStream(raw))
                            {
                                zip.Save(ns);
                            }
                        }
                    }
                    else
                        zip.Save(zipFileToCreate);
                }

                BasicVerifyZip(Path.GetFileName(zipFileToCreate), password);

                Assert.AreEqual<int>(files.Length, TestUtilities.CountEntries(zipFileToCreate),
                                     "Trial ({0},{1}): The zip file created has the wrong number of entries.", cycle, k);
            }
        }
Exemplo n.º 5
0
        public void Update_MultipleSaves_wi10319()
        {
            string zipFileToCreate = "MultipleSaves_wi10319.zip";

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

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

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

                        data.Seek(0, SeekOrigin.Begin);

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

                    }
                }
            }
        }
Exemplo n.º 6
0
        public void ZipFile_JitStream_CloserTwice_wi10489()
        {
            int fileCount = 20 + _rnd.Next(20);
            string zipFileToCreate = "CloserTwice.zip";
            string dirToZip = "fodder";
            var files = TestUtilities.GenerateFilesFlat(dirToZip, fileCount, 100, 72000);

            OpenDelegate opener = (name) =>
                {
                    TestContext.WriteLine("Opening {0}", name);
                    Stream s = File.OpenRead(Path.Combine(dirToZip,name));
                    return s;
                };

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

            TestContext.WriteLine("Creating zipfile {0}", zipFileToCreate);
            using (var zip = new ZipFile())
            {
                foreach (var file in files)
                {
                    zip.AddEntry(Path.GetFileName(file),opener,closer);
                }
                zip.Save(zipFileToCreate);
            }

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

            BasicVerifyZip(zipFileToCreate);
        }
        public void WZA_InMemory_wi8493a()
        {
            if (!WinZipIsPresent)
                throw new Exception("no winzip! [WZA_InMemory_wi8493a]");

            string zipFileToCreate = "WZA_InMemory_wi8493a.zip";
            string password = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());

            string[] TextFiles = new string[25 + _rnd.Next(8)];
            for (int i = 0; i < TextFiles.Length; i++)
            {
                TextFiles[i] = Path.Combine(TopLevelDir, String.Format("TextFile{0}.txt", i));
                TestUtilities.CreateAndFillFileText(TextFiles[i], _rnd.Next(14000) + 13000);
            }

            using (MemoryStream ms = new MemoryStream())
            {
                using (var zip = new ZipFile())
                {
                    zip.Password = password;
                    zip.Encryption = EncryptionAlgorithm.WinZipAes256;
                    zip.AddEntry("Readme.txt", "Hello, World! ABC ABC ABC ABC ABCDE ABC ABCDEF ABC ABCD");
                    zip.AddFiles(TextFiles, "files");
                    zip.Save(ms);
                }
                File.WriteAllBytes(zipFileToCreate,ms.ToArray());

                BasicVerifyZip(zipFileToCreate, password);
            }
        }
Exemplo n.º 8
0
        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 WZA_SmallBuffers_wi7967()
        {
            if (!WinZipIsPresent)
                throw new Exception("no winzip! [WZA_SmallBuffers_wi7967]");

            Directory.SetCurrentDirectory(TopLevelDir);

            string password = Path.GetRandomFileName() + Path.GetFileNameWithoutExtension(Path.GetRandomFileName());

            int[] sizes = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13, 21, 35, 93 };
            for (int i = 0; i < sizes.Length; i++)
            {
                string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("WZA_SmallBuffers_wi7967-{0}.zip", i));
                //MemoryStream zippedStream = new MemoryStream();
                byte[] buffer = new byte[sizes[i]];
                _rnd.NextBytes(buffer);
                MemoryStream source = new MemoryStream(buffer);

                using (var zip = new ZipFile())
                {
                    source.Seek(0, SeekOrigin.Begin);
                    zip.Password = password;
                    zip.Encryption = EncryptionAlgorithm.WinZipAes256;
                    zip.AddEntry(Path.GetRandomFileName(), source);
                    zip.Save(zipFileToCreate);
                }

                BasicVerifyZip(zipFileToCreate, password);
            }
        }
Exemplo n.º 10
0
        public void WZA_InMemory_wi8493()
        {
            if (!WinZipIsPresent)
                throw new Exception("no winzip! [WZA_InMemory_wi8493]");

            string password = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());

            using (MemoryStream ms = new MemoryStream())
            {
                for (int m = 0; m < 2; m++)
                {
                    string zipFileToCreate =
                        String.Format("WZA_InMemory_wi8493-{0}.zip", m);

                    using (var zip = new ZipFile())
                    {
                        zip.Password = password;
                        zip.Encryption = EncryptionAlgorithm.WinZipAes256;
                        zip.AddEntry(Path.GetRandomFileName(), "Hello, World!");
                        if (m==1)
                            zip.Save(ms);
                        else
                            zip.Save(zipFileToCreate);
                    }

                    if (m==1)
                        File.WriteAllBytes(zipFileToCreate,ms.ToArray());

                    BasicVerifyZip(zipFileToCreate, password);
                }
            }
        }
Exemplo n.º 11
0
        public void WZA_RemoveEntryAndSave()
        {
            if (!WinZipIsPresent)
                throw new Exception("no winzip! [WZA_RemoveEntryAndSave]");

            // make a few text files
            string[] TextFiles = new string[5];
            for (int i = 0; i < TextFiles.Length; i++)
            {
                TextFiles[i] = Path.Combine(TopLevelDir, String.Format("TextFile{0}.txt", i));
                TestUtilities.CreateAndFillFileText(TextFiles[i], _rnd.Next(4000) + 5000);
            }
            TestContext.WriteLine(new String('=', 66));
            TestContext.WriteLine("RemoveEntryAndSave()");
            string password = Path.GetRandomFileName();
            for (int k = 0; k < 2; k++)
            {
                TestContext.WriteLine(new String('-', 55));
                TestContext.WriteLine("Trial {0}", k);
                string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("RemoveEntryAndSave-{0}.zip", k));

                // create the zip: add some files, and Save() it
                using (ZipFile zip = new ZipFile())
                {
                    if (k == 1)
                    {
                        TestContext.WriteLine("Specifying a password...");
                        zip.Password = password;
                        zip.Encryption = EncryptionAlgorithm.WinZipAes256;
                    }
                    for (int i = 0; i < TextFiles.Length; i++)
                        zip.AddFile(TextFiles[i], "");

                    zip.AddEntry("Readme.txt", "This is the content of the file. Ho ho ho!");
                    TestContext.WriteLine("Save...");
                    zip.Save(zipFileToCreate);
                }

                if (k == 1)
                    BasicVerifyZip(zipFileToCreate, password);

                // remove a file and re-Save
                using (ZipFile zip2 = ZipFile.Read(zipFileToCreate))
                {
                    int entryToRemove = _rnd.Next(TextFiles.Length);
                    TestContext.WriteLine("Removing an entry...: {0}", Path.GetFileName(TextFiles[entryToRemove]));
                    zip2.RemoveEntry(Path.GetFileName(TextFiles[entryToRemove]));
                    zip2.Save();
                }

                // Verify the files are in the zip
                Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), TextFiles.Length,
                                     String.Format("Trial {0}: The Zip file has the wrong number of entries.", k));

                if (k == 1)
                    BasicVerifyZip(zipFileToCreate, password);
            }
        }
Exemplo n.º 12
0
        public void WZA_OneZeroByteFile_wi11131()
        {
            string zipF = "WZA_OneZeroByteFile_wi11131.zip";
            TestContext.WriteLine("Create file {0}", zipF);
            using (ZipFile zipFile = new ZipFile())
            {
                zipFile.Encryption = EncryptionAlgorithm.WinZipAes256;
                zipFile.Password = TestUtilities.GenerateRandomPassword();
                zipFile.AddEntry("dummy", new byte[0]);
                using (var fs = File.Create(zipF))
                {
                    zipFile.Save(fs);
                }
            }

            BasicVerifyZip(zipF);
            Assert.AreEqual<int>(1, TestUtilities.CountEntries(zipF));
        }
Exemplo n.º 13
0
        public void CodePage_UpdateZip_AlternateEncoding_wi10180()
        {
            System.Text.Encoding JIS = System.Text.Encoding.GetEncoding("shift_jis");
            TestContext.WriteLine("The CP for JIS is: {0}", JIS.CodePage);
            ReadOptions options = new ReadOptions { Encoding = JIS };
            string[] filenames = {
                "日本語.txt",
                "日本語テスト.txt"
            };

            // three trials: one for old-style
            // ProvisionalAlternateEncoding, one for "AsNecessary"
            // and one for "Always"
            for (int j=0; j < 3; j++)
            {
                string zipFileToCreate = String.Format("wi10180-{0}.zip", j);

                // pass 1 - create it
                TestContext.WriteLine("Create zip, cycle {0}...", j);
                using (var zip = new ZipFile())
                {
                    switch (j)
                    {
                        case 0:
#pragma warning disable 618
                            zip.ProvisionalAlternateEncoding = JIS;
#pragma warning restore 618
                            break;
                        case 1:
                            zip.AlternateEncoding = JIS;
                            zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                            break;
                        case 2:
                            zip.AlternateEncoding = JIS;
                            zip.AlternateEncodingUsage = ZipOption.Always;
                            break;
                    }
                    zip.AddEntry(filenames[0], "This is the content for entry (" + filenames[0] + ")");
                    TestContext.WriteLine("adding file: {0}", filenames[0]);
                    zip.Save(zipFileToCreate);
                }

                // pass 2 - read and update it
                TestContext.WriteLine("Update zip...");
                using (var zip0 = ZipFile.Read(zipFileToCreate, options))
                {
                    foreach (var e in zip0)
                    {
                        TestContext.WriteLine("existing entry name: {0}  encoding: {1}",
                                              e.FileName, e.AlternateEncoding.EncodingName );
                        Assert.AreEqual<System.Text.Encoding>
                            (options.Encoding, e.AlternateEncoding);
                    }
                    zip0.AddEntry(filenames[1], "This is more content..." + System.DateTime.UtcNow.ToString("G"));
                    TestContext.WriteLine("adding file: {0}", filenames[1]);
                    zip0.Save();
                }

                // pass 3 - verify the filenames, again
                TestContext.WriteLine("Verify zip...");
                using (var zip0 = ZipFile.Read(zipFileToCreate, options))
                {
                    foreach (string f in filenames)
                    {
                        Assert.AreEqual<string>(f, zip0[f].FileName,
                                                "The FileName was not expected, (cycle {0}) ", j);
                    }
                }
            }
        }
Exemplo n.º 14
0
        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(zipFileToCreate))
            {
                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();
            }

            int entryCount = 0;
            using (ZipFile zip2 = ZipFile.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);
        }
Exemplo n.º 15
0
        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 = ZipFile.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);
                        }
                    }
                }
            }
        }
Exemplo n.º 16
0
        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.");

            }

        }
Exemplo n.º 17
0
        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 testBin = TestUtilities.GetTestBinDir(CurrentDir);
            string fileToZip = Path.Combine(testBin, "Ionic.Zip.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 = ZipFile.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("");
                }
            }
        }
Exemplo n.º 18
0
        public void UpdateZip_ChangeMetadata_AES()
        {
            Directory.SetCurrentDirectory(TopLevelDir);
            string zipFileToCreate = Path.Combine(TopLevelDir, "UpdateZip_ChangeMetadata_AES.zip");
            string subdir = Path.Combine(TopLevelDir, "A");
            Directory.CreateDirectory(subdir);

            // create the files
            int numFilesToCreate = _rnd.Next(13) + 24;
            //int numFilesToCreate = 2;
            string filename = null;
            for (int j = 0; j < numFilesToCreate; j++)
            {
                filename = Path.Combine(subdir, String.Format("file{0:D3}.txt", j));
                TestUtilities.CreateAndFillFileText(filename, _rnd.Next(34000) + 5000);
                //TestUtilities.CreateAndFillFileText(filename, 500);
            }

            string password = Path.GetRandomFileName() + Path.GetFileNameWithoutExtension(Path.GetRandomFileName());

            using (var zip = new ZipFile())
            {
                zip.Password = password;
                zip.Encryption = EncryptionAlgorithm.WinZipAes256;
                zip.AddFiles(Directory.GetFiles(subdir), "");
                zip.Save(zipFileToCreate);
            }

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

            // test extract (and implicitly check CRCs, passwords, etc)
            VerifyZip(zipFileToCreate, password);

            byte[] buffer = new byte[_rnd.Next(10000) + 10000];
            _rnd.NextBytes(buffer);
            using (var zip = ZipFile.Read(zipFileToCreate))
            {
                // modify the metadata for an entry
                zip[0].LastModified = DateTime.Now - new TimeSpan(7 * 31, 0, 0);
                zip.Password = password;
                zip.Encryption = EncryptionAlgorithm.WinZipAes256;
                zip.AddEntry(Path.GetRandomFileName(), buffer);
                zip.Save();
            }

            // Verify the correct number of files are in the zip
            Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), numFilesToCreate + 1,
                                 "Fie! The updated Zip file has the wrong number of entries.");

            // test extract (and implicitly check CRCs, passwords, etc)
            VerifyZip(zipFileToCreate, password);
        }
Exemplo n.º 19
0
        public void SortedSave()
        {
            var rtg = new RandomTextGenerator();

            WriteDelegate writer = (name, stream) =>
                {
                    byte[] buffer = System.Text.Encoding.ASCII.GetBytes(rtg.Generate(_rnd.Next(2000) + 200));
                    stream.Write(buffer, 0, buffer.Length);
                };

            int numEntries = _rnd.Next(256) + 48;

            // Two trials, one with sorted output, and the other with non-sorted output.
            for (int m = 0; m < 2; m++)
            {
                string zipFileToCreate = Path.Combine(TopLevelDir,
                                                      String.Format("SortedSave-{0}.zip", m));
                using (var zip = new ZipFile())
                {
                    for (int i = 0; i < numEntries; i++)
                    {
                        // I need the randomness in the first part, to force the sort.
                        string filename = String.Format("{0}-{1:000}.txt",
                                                        TestUtilities.GenerateRandomAsciiString(6), i);
                        zip.AddEntry(filename, writer);
                    }

                    zip.SortEntriesBeforeSaving = (m == 1);
                    zip.Save(zipFileToCreate);
                }

                using (var zip = ZipFile.Read(zipFileToCreate))
                {
                    bool sorted = true;
                    for (int i = 0; i < zip.Entries.Count - 1 && sorted; i++)
                    {
                        for (int j = i; j < zip.Entries.Count && sorted; j++)
                        {
                            if (String.Compare(zip[i].FileName, zip[j].FileName, StringComparison.OrdinalIgnoreCase) > 0)
                            {
                                sorted = false;
                            }
                        }
                    }

                    Assert.IsTrue((((m == 1) && sorted) || ((m == 0) && !sorted)),
                        "Unexpected sort results");
                }
            }
        }
Exemplo n.º 20
0
        public void Update_MultipleSavesWithRename_wi10544()
        {
            // select the name of the zip file
            string zipFileToCreate = Path.Combine(TopLevelDir, "Update_MultipleSaves_wi10319.zip");
            string entryName = "Entry1.txt";

            TestContext.WriteLine("Creating zip file... ");
            using (var zip = new ZipFile())
            {
                string firstline = "This is the first line in the Entry.\n";
                byte[] a = System.Text.Encoding.ASCII.GetBytes(firstline.ToCharArray());

                zip.AddEntry(entryName, a);
                zip.Save(zipFileToCreate);
            }

            int N = _rnd.Next(34) + 59;
            for (int i = 0; i < N; i++)
            {
                string tempZipFile = "AppendToEntry.zip.tmp" + i;

                TestContext.WriteLine("Update cycle {0}... ", i);
                using (var zip1 = ZipFile.Read(zipFileToCreate))
                {
                    using (var zip = new ZipFile())
                    {
                        zip.AddEntry(entryName, (name, stream) =>
                            {
                                var src = zip1[name].OpenReader();
                                int n;
                                byte[] b = new byte[2048];
                                while ((n = src.Read(b, 0, b.Length)) > 0)
                                    stream.Write(b, 0, n);

                                string update = String.Format("Updating zip file {0} at {1}\n", i, DateTime.Now.ToString("G"));
                                byte[] a = System.Text.Encoding.ASCII.GetBytes(update.ToCharArray());
                                stream.Write(a, 0, a.Length);
                            });

                        zip.Save(tempZipFile);
                    }
                }

                File.Delete(zipFileToCreate);
                System.Threading.Thread.Sleep(1400);
                File.Move(tempZipFile, zipFileToCreate);
            }

        }
Exemplo n.º 21
0
        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 = ZipFile.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 = ZipFile.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"]);
            }

        }
Exemplo n.º 22
0
        public void JitStream_Update_wi13899()
        {
            int fileCount = 12 + _rnd.Next(16);
            string dirToZip = "fodder";
            var files = TestUtilities.GenerateFilesFlat(dirToZip, fileCount, 100, 72000);
            OpenDelegate opener = (name) =>
                {
                    TestContext.WriteLine("Opening {0}", name);
                    Stream s = File.OpenRead(Path.Combine(dirToZip,name));
                    return s;
                };

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

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

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

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

                    BasicVerifyZip(zipFileToCreate);

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

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

                BasicVerifyZip(zipFileToCreate);
                // verify checksum here?
            }
        }
Exemplo n.º 23
0
        public void Extract_AfterSaveNoDispose()
        {
            string zipFileToCreate = Path.Combine(TopLevelDir, "Extract_AfterSaveNoDispose.zip");
            string inputString = "<AAA><bob><YourUncle/></bob><w00t/></AAA>";

            using (ZipFile zip1 = new ZipFile())
            {
                MemoryStream ms1 = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(inputString));
                zip1.AddEntry("woo\\Test.xml", ms1);
                zip1.Save(zipFileToCreate);

                MemoryStream ms2 = new MemoryStream();
                zip1["Woo/Test.xml"].Extract(ms2);
                ms2.Seek(0, SeekOrigin.Begin);

                var sw1 = new StringWriter();
                var w1 = new XTWFND(sw1);

                var d1 = new System.Xml.XmlDocument();
                d1.Load(ms2);
                d1.Save(w1);

                var sw2 = new StringWriter();
                var w2 = new XTWFND(sw2);
                var d2 = new System.Xml.XmlDocument();
                d2.Load(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(inputString)));
                d2.Save(w2);

                Assert.AreEqual<String>(sw2.ToString(), sw1.ToString(), "Unexpected value on extract ({0}).", sw1.ToString());
            }
        }
Exemplo n.º 24
0
        public void AddEntry_JitProvided()
        {
            for (int i = 0; i < crypto.Length; i++)
            {
                for (int k = 0; k < compLevels.Length; k++)
                {
                    string zipFileToCreate = String.Format("AddEntry_JitProvided.{0}.{1}.zip", i, k);
                    string dirToZip = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
                    var files = TestUtilities.GenerateFilesFlat(dirToZip);
                    string password = Path.GetRandomFileName();

                    using (var zip = new ZipFile())
                    {
                        TestContext.WriteLine("=================================");
                        TestContext.WriteLine("Creating {0}...", Path.GetFileName(zipFileToCreate));
                        TestContext.WriteLine("Encryption({0})  Compression({1})  pw({2})",
                                              crypto[i].ToString(), compLevels[k].ToString(), password);

                        zip.Password = password;
                        zip.Encryption = crypto[i];
                        zip.CompressionLevel = compLevels[k];

                        foreach (var file in files)
                            zip.AddEntry(file,
                                         (name) => File.OpenRead(name),
                                         (name, stream) => stream.Close()
                                         );
                        zip.Save(zipFileToCreate);
                    }

                    if (crypto[i] == EncryptionAlgorithm.None)
                        BasicVerifyZip(zipFileToCreate);
                    else
                        BasicVerifyZip(zipFileToCreate, password);

                    Assert.AreEqual<int>(files.Length, TestUtilities.CountEntries(zipFileToCreate),
                                         "Trial ({0},{1}): The zip file created has the wrong number of entries.", i, k);
                }
            }
        }
Exemplo n.º 25
0
        public void Test_AddUpdateFileFromStream()
        {
            string[] passwords = { null, "Password", TestUtilities.GenerateRandomPassword(), "A" };
            for (int k = 0; k < passwords.Length; k++)
            {
                string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("Test_AddUpdateFileFromStream-{0}.zip", k));
                string[] inputStrings = new string[]
                        {
                            TestUtilities.LoremIpsum.Substring(_rnd.Next(5), 170 + _rnd.Next(25)),
                            TestUtilities.LoremIpsum.Substring(100 + _rnd.Next(40), 180+ _rnd.Next(30))
                        };

                // add entries to a zipfile.
                // use a password.(possibly null)
                using (ZipFile zip1 = new ZipFile())
                {
                    zip1.Password = passwords[k];
                    for (int i = 0; i < inputStrings.Length; i++)
                    {
                        zip1.AddEntry(String.Format("Lorem{0}.txt", i + 1), inputStrings[i]);
                    }
                    zip1.Save(zipFileToCreate);
                }

                using (ZipFile zip2 = ZipFile.Read(zipFileToCreate))
                {
                    zip2["Lorem2.txt"].Password = passwords[k];
                    string output = StreamToStringUTF8(zip2["Lorem2.txt"].OpenReader());

                    Assert.AreEqual<String>(output, inputStrings[1], "Trial {0}: Read entry 2 after create: Unexpected value on extract.", k);

                    zip2["Lorem1.txt"].Password = passwords[k];
                    Stream s = zip2["Lorem1.txt"].OpenReader();
                    output = StreamToStringUTF8(s);

                    Assert.AreEqual<String>(output, inputStrings[0], "Trial {0}: Read entry 1 after create: Unexpected value on extract.", k);
                }


                // update an entry in the zipfile.  For this pass, don't use a password.
                string UpdateString = "This is the updated content.  It will replace the original content, added from a string.";
                using (ZipFile zip3 = ZipFile.Read(zipFileToCreate))
                {
                    var ms1 = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(UpdateString));
                    zip3.UpdateEntry("Lorem1.txt", ms1);
                    zip3.Save();
                }

                using (ZipFile zip4 = ZipFile.Read(zipFileToCreate))
                {
                    string output = StreamToStringUTF8(zip4["Lorem1.txt"].OpenReader());
                    Assert.AreEqual<String>(output, UpdateString, "Trial {0}: Reading after update: Unexpected value on extract.", k);
                }
            }
        }
Exemplo n.º 26
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);
        }
Exemplo n.º 27
0
        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(zipFileToCreate, Encoding.UTF8))
            {
                zip1.Comment = cyrillicComment;
                zip1.AddEntry("entry", "this is the content of the added entry");
                zip1.Save();
            }

            string comment2 = null;
            TestContext.WriteLine("==== checking zip");
            var options = new ReadOptions {
                Encoding = Encoding.UTF8
            };
            using (ZipFile zip2 = ZipFile.Read(zipFileToCreate, options))
            {
                comment2 = zip2.Comment;
            }

            Assert.AreEqual<String>(cyrillicComment, comment2,
                                    "The comments are not equal.");
        }