public void UnicodeComment_wi10392() { const string zipFileToCreate = "UnicodeComment_wi10392.zip"; const string cyrillicComment = "Hello, Привет"; TestContext.WriteLine("{0}", zipFileToCreate); TestContext.WriteLine("==== creating zip"); using (ZipFile zip1 = new ZipFile(System.Text.Encoding.UTF8)) { zip1.Comment = cyrillicComment; zip1.AddEntry("entry", "this is the content of the added entry"); zip1.Save(zipFileToCreate); } string comment2 = null; TestContext.WriteLine("==== checking zip"); var options = new ReadOptions { Encoding = System.Text.Encoding.UTF8 }; using (ZipFile zip2 = FileSystemZip.Read(zipFileToCreate, options)) { comment2 = zip2.Comment; } Assert.AreEqual <String>(cyrillicComment, comment2, "The comments are not equal."); }
public void Error_Read_EmptyZipFile() { string zipFileToRead = Path.Combine(TopLevelDir, "Read_BadFile.zip"); string newFile = Path.GetTempFileName(); _FilesToRemove.Add(newFile); File.Move(newFile, zipFileToRead); newFile = Path.GetTempFileName(); _FilesToRemove.Add(newFile); string fileToAdd = Path.Combine(TopLevelDir, "EmptyFile.txt"); File.Move(newFile, fileToAdd); try { using (ZipFile zip = FileSystemZip.Read(zipFileToRead)) { zip.AddFile(fileToAdd, ""); zip.Save(zipFileToRead); } } catch (System.Exception exc1) { throw new ZipException("expected", exc1); } }
private void _CheckUnicodeZip(string filename, int j) { int i = 0; // Verify that the filenames do, or do not, match the // names that were added. They will match if unicode // was used (j!=1) or if the filename used was the first // in the formats list (k==0). using (ZipFile zip2 = FileSystemZip.Read(filename)) { foreach (ZipEntry e in zip2) { int k = i % miscNameFormats.Length; string fname = String.Format(miscNameFormats[k], i); if (j != 1 || k == 0) { Assert.AreEqual <String>(fname, e.FileName, "cycle ({0},{1},{2})", i, j, k); } else { Assert.AreNotEqual <String>(fname, e.FileName, "cycle ({0},{1},{2})", i, j, k); } i++; } } }
public void Progress_ReadFile() { Directory.SetCurrentDirectory(TopLevelDir); string zipFileToCreate = Path.Combine(TopLevelDir, "Progress_ReadFile.zip"); string dirToZip = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()); var files = TestUtilities.GenerateFilesFlat(dirToZip); using (ZipFile zip = new ZipFile()) { zip.AddFiles(files); zip.Save(zipFileToCreate); } int count = TestUtilities.CountEntries(zipFileToCreate); Assert.IsTrue(count > 0); var options = new ReadOptions { StatusMessageWriter = new StringWriter(), ReadProgress = ReadProgress1 }; using (ZipFile zip = FileSystemZip.Read(zipFileToCreate, options)) { // this should be fine zip.RemoveEntry(zip[1]); zip.Save(zipFileToCreate); } TestContext.WriteLine(options.StatusMessageWriter.ToString()); Assert.AreEqual <Int32>(count, TestUtilities.CountEntries(zipFileToCreate) + 1); }
private void _Internal_ReadZip(string zipFileToRead, string password, int expectedFilesExtracted) { Directory.SetCurrentDirectory(TopLevelDir); Assert.IsTrue(File.Exists(zipFileToRead), "The zip file '{0}' does not exist.", zipFileToRead); // extract all the files int actualFilesExtracted = 0; string extractDir = String.Format("Extract{0}", zipCount++); using (ZipFile zip2 = FileSystemZip.Read(zipFileToRead)) { //zip2.Password = password; foreach (ZipEntry e in zip2) { if (!e.IsDirectory) { if (password == "-null-") { e.Extract(extractDir); } else { e.ExtractWithPassword(extractDir, password); } actualFilesExtracted++; } } } Assert.AreEqual <int>(expectedFilesExtracted, actualFilesExtracted); }
[Timeout(5 * 60 * 1000)] // to protect against stuck file locks public void Spanned_WinZip_Zip_wi13691() { if (!WinZipIsPresent) { throw new Exception("WinZip is not present"); } TestContext.WriteLine("Creating fodder files... {0}", DateTime.Now.ToString("G")); var contentDir = CreateSomeFiles(); var filesToAdd = new List <String>(Directory.GetFiles(contentDir)); int[] segSizes = { 128, 256, 512 }; // Save as segmented, then read/extract with winzip unzip // for various segment sizes. for (int k = 0; k < segSizes.Length; k++) { string trialDir = String.Format("trial.{0}", k); Directory.CreateDirectory(trialDir); string nameOfParts = Path.Combine(trialDir, "InitialSave." + k); string zipFile1 = nameOfParts + ".zip"; TestContext.WriteLine(""); TestContext.WriteLine("Creating zip... T({0})...{1}", k, DateTime.Now.ToString("G")); // with WinZip, must produce a segmented zip in two // steps: first create the regular zip, then split it. // step 1: create the regular zip string args = String.Format("-a -p -r -yx step1.zip \"{0}\"", contentDir); string wzzipOut = this.Exec(wzzip, args); // step 2: split the existing zip // "wzzip -ys[size] archivetosplit.zip nameofparts " args = String.Format("-ys{0} step1.zip {1}", segSizes[k], zipFile1 //nameOfParts ); wzzipOut = this.Exec(wzzip, args); TestContext.WriteLine(""); TestContext.WriteLine("Extracting..."); string extractDir = Path.Combine(trialDir, "extract"); Directory.CreateDirectory(extractDir); using (var zip1 = FileSystemZip.Read(zipFile1)) { foreach (var e in zip1) { TestContext.WriteLine(" {0}", e.FileName); e.Extract(extractDir); } } string[] filesUnzipped = Directory.GetFiles(extractDir); Assert.AreEqual <int>(filesToAdd.Count, filesUnzipped.Length, "Incorrect number of files extracted, trail {0}", k); } }
public void Spanned_Resave_Extract() { TestContext.WriteLine("Creating fodder files... {0}", DateTime.Now.ToString("G")); var contentDir = CreateSomeFiles(); var filesToAdd = new List <String>(Directory.GetFiles(contentDir)); int[] segSizes = { 128, 256, 512 }; // for various segment sizes for (int k = 0; k < segSizes.Length; k++) { string trialDir = String.Format("trial.{0}", k); Directory.CreateDirectory(trialDir); string zipFile1 = Path.Combine(trialDir, "InitialSave." + k + ".zip"); string zipFile2 = Path.Combine(trialDir, "Updated." + k + ".zip"); string extractDir = Path.Combine(trialDir, "extract"); TestContext.WriteLine(""); TestContext.WriteLine("Creating zip... T({0})...{1}", k, DateTime.Now.ToString("G")); using (var zip1 = new ZipFile()) { zip1.AddFiles(filesToAdd, ""); zip1.MaxOutputSegmentSize = segSizes[k] * 1024; zip1.Save(zipFile1); } TestContext.WriteLine(""); TestContext.WriteLine("Re-saving..."); using (var zip2 = FileSystemZip.Read(zipFile1)) { zip2.MaxOutputSegmentSize = segSizes[k] * 1024; zip2.Save(zipFile2); // make sure we aren't accidentally using InitialSave.*.zip data TestContext.WriteLine(""); TestContext.WriteLine("Deleting initial archive..."); string[] filesToDelete = Directory.GetFiles(trialDir, "InitialSave.*"); foreach (var file in filesToDelete) { File.Delete(file); } // this should be using the Updated.*.zip file stream TestContext.WriteLine(""); TestContext.WriteLine("Extracting..."); Directory.CreateDirectory(extractDir); foreach (var e in zip2) { TestContext.WriteLine(" {0}", e.FileName); e.Extract(extractDir); } } string[] filesUnzipped = Directory.GetFiles(extractDir); Assert.AreEqual <int>(filesToAdd.Count, filesUnzipped.Length, "Incorrect number of files extracted."); } }
public void UnicodeUpdate_wi12744() { const string specialEntryName = "Привет.txt"; // two passes: one that uses the old "useUnicodeAsNecessary" property, // and the second that uses the newer property. for (int k = 0; k < 2; k++) { string zipFileToCreate = String.Format("UnicodeUpdate_wi12744-{0}.zip", k); TestContext.WriteLine("{0}", zipFileToCreate); TestContext.WriteLine("==== creating zip, trial {0}", k); using (ZipFile zip1 = new ZipFile()) { if (k == 0) { #pragma warning disable 618 zip1.UseUnicodeAsNecessary = true; #pragma warning restore 618 } else { zip1.AlternateEncoding = System.Text.Encoding.UTF8; zip1.AlternateEncodingUsage = ZipOption.AsNecessary; } zip1.AddEntry(specialEntryName, "this is the content of the added entry"); zip1.Save(zipFileToCreate); } TestContext.WriteLine("==== create a directory with 2 addl files in it"); string subdir = Path.Combine(TopLevelDir, "files" + k); Directory.CreateDirectory(subdir); for (int i = 0; i < 2; i++) { var filename = Path.Combine(subdir, "file" + i + ".txt"); TestUtilities.CreateAndFillFileText(filename, _rnd.Next(5000) + 2000); } TestContext.WriteLine("==== update the zip"); using (ZipFile zip2 = FileSystemZip.Read(zipFileToCreate)) { zip2.AddDirectory(subdir); zip2.Save(zipFileToCreate); } TestContext.WriteLine("==== check the original file in the zip"); using (ZipFile zip3 = FileSystemZip.Read(zipFileToCreate)) { var e = zip3[specialEntryName]; Assert.IsTrue(e != null, "Entry not found"); Assert.IsTrue(e.FileName == specialEntryName, "name mismatch"); } } }
[ExpectedException(typeof(ZipException))] // not sure which exception - could be one of several. public void Error_ReadCorruptedZipFile_Passwords() { string zipFileToCreate = Path.Combine(TopLevelDir, "Read_CorruptedZipFile_Passwords.zip"); Directory.SetCurrentDirectory(TopLevelDir); // the list of filenames to add to the zip string[] filenames = { Path.Combine(SourceDir, "Tools", TestUtilities.GetBinDir("Zipit"), "Zipit.exe"), Path.Combine(SourceDir, TestUtilities.GetBinDir("Zip.Portable"), "Zip.Portable.xml"), Path.Combine(SourceDir, "Tools", "WinFormsApp", "Icon2.res"), }; // passwords to use for those entries string[] passwords = { "12345678", "0987654321", }; // create the zipfile, adding the files int j = 0; using (ZipFile zip = new ZipFile()) { for (j = 0; j < filenames.Length; j++) { zip.Password = passwords[j % passwords.Length]; zip.AddFile(filenames[j], ""); } zip.Save(zipFileToCreate); } IntroduceCorruption(zipFileToCreate); try { // read the corrupted zip - this should fail in some way using (ZipFile zip = FileSystemZip.Read(zipFileToCreate)) { for (j = 0; j < filenames.Length; j++) { ZipEntry e = zip[Path.GetFileName(filenames[j])]; System.Console.WriteLine("name: {0} compressed: {1} has password?: {2}", e.FileName, e.CompressedSize, e.UsesEncryption); Assert.IsTrue(e.UsesEncryption, "The entry does not use encryption"); e.ExtractWithPassword("unpack", passwords[j % passwords.Length]); } } } catch (Exception exc1) { throw new ZipException("expected", exc1); } }
public void Error_NonZipFile_wi11743() { // try reading an empty, extant file as a zip file string zipFileToRead = Path.GetTempFileName(); _FilesToRemove.Add(zipFileToRead); using (ZipFile zip = FileSystemZip.Read(zipFileToRead)) { zip.AddEntry("EntryName1.txt", "This is the content"); zip.Save(zipFileToRead); } }
public void Password_MultipleEntriesDifferentPasswords() { string ZipFileToCreate = Path.Combine(TopLevelDir, "Password_MultipleEntriesDifferentPasswords.zip"); Assert.IsFalse(File.Exists(ZipFileToCreate), "The temporary zip file '{0}' already exists.", ZipFileToCreate); Directory.SetCurrentDirectory(TopLevelDir); string[] filenames = { Path.Combine(SourceDir, "Tools", TestUtilities.GetBinDir("Zipit"), "Zipit.exe"), Path.Combine(SourceDir, TestUtilities.GetBinDir("Zip.Portable"), "Zip.Portable.xml"), }; string[] checksums = { TestUtilities.GetCheckSumString(filenames[0]), TestUtilities.GetCheckSumString(filenames[1]), }; string[] passwords = { "12345678", "0987654321", }; int j = 0; using (ZipFile zip = new ZipFile()) { for (j = 0; j < filenames.Length; j++) { zip.Password = passwords[j]; zip.AddFile(filenames[j], ""); } zip.Save(ZipFileToCreate); } Assert.AreEqual <int>(TestUtilities.CountEntries(ZipFileToCreate), filenames.Length, "The zip file created has the wrong number of entries."); using (ZipFile zip = FileSystemZip.Read(ZipFileToCreate)) { for (j = 0; j < filenames.Length; j++) { zip[Path.GetFileName(filenames[j])].ExtractWithPassword("unpack", ExtractExistingFileAction.OverwriteSilently, passwords[j]); string newpath = Path.Combine("unpack", filenames[j]); string chk = TestUtilities.GetCheckSumString(newpath); Assert.AreEqual <string>(checksums[j], chk, "File checksums do not match."); } } }
public void MalformedZip() { string filePath = Path.GetTempFileName(); _FilesToRemove.Add(filePath); File.WriteAllText(filePath, "asdfasdf"); string outputDirectory = Path.GetTempPath(); using (ZipFile zipFile = FileSystemZip.Read(filePath)) { zipFile.ExtractAll(outputDirectory); } }
internal string BasicVerifyZip(string zipfile, string password, bool emitOutput, EventHandler <ExtractProgressEventArgs> extractProgress) { // basic verification of the zip file - can it be extracted? // The extraction tool will verify checksums and passwords, as appropriate #if NOT if (WinZipIsPresent) { TestContext.WriteLine("Verifying zip file {0} with WinZip", zipfile); string args = (password == null) ? String.Format("-t {0}", zipfile) : String.Format("-s{0} -t {1}", password, zipfile); string wzunzipOut = this.Exec(wzunzip, args, true, emitOutput); } else #endif { TestContext.WriteLine("Verifying zip file {0} with DotNetZip", zipfile); ReadOptions options = new ReadOptions(); if (emitOutput) { options.StatusMessageWriter = new StringWriter(); } string extractDir = "verify"; int c = 0; while (Directory.Exists(extractDir + c)) { c++; } extractDir += c; using (ZipFile zip2 = FileSystemZip.Read(zipfile, options)) { zip2.Password = password; if (extractProgress != null) { zip2.ExtractProgress += extractProgress; } zip2.ExtractAll(extractDir); } // emit output, as desired if (emitOutput) { TestContext.WriteLine("{0}", options.StatusMessageWriter.ToString()); } return(extractDir); } }
[Timeout(5 * 60 * 1000)] // to protect against stuck file locks public void Spanned_InfoZip_Zip_wi13691() { if (!InfoZipIsPresent) { throw new Exception("InfoZip is not present"); } TestContext.WriteLine("Creating fodder files... {0}", DateTime.Now.ToString("G")); var contentDir = CreateSomeFiles(); var filesToAdd = new List <String>(Directory.GetFiles(contentDir)); int[] segSizes = { 128, 256, 512 }; // Save as segmented, then read/extract with winzip unzip // for various segment sizes. for (int k = 0; k < segSizes.Length; k++) { string trialDir = String.Format("trial.{0}", k); Directory.CreateDirectory(trialDir); string zipFile1 = Path.Combine(trialDir, "InitialSave." + k + ".zip"); TestContext.WriteLine(""); TestContext.WriteLine("Creating zip... T({0})...{1}", k, DateTime.Now.ToString("G")); string args = String.Format("-s {0}k {1} -r \"{2}\"", segSizes[k], zipFile1, contentDir); this.Exec(infoZip, args); TestContext.WriteLine(""); TestContext.WriteLine("Extracting..."); string extractDir = Path.Combine(trialDir, "extract"); Directory.CreateDirectory(extractDir); using (var zip1 = FileSystemZip.Read(zipFile1)) { foreach (var e in zip1) { TestContext.WriteLine(" {0}", e.FileName); e.Extract(extractDir); } } string[] filesUnzipped = Directory.GetFiles(Path.Combine(extractDir, contentDir)); Assert.AreEqual <int>(filesToAdd.Count, filesUnzipped.Length, "Incorrect number of files extracted, trail {0}", k); } }
public void Error_FileNotAvailableFails() { // verify the correct exception is being thrown string zipFileToCreate = Path.Combine(TopLevelDir, "Error_FileNotAvailableFails.zip"); // create a zip file with no entries using (var zipfile = new ZipFile()) { zipfile.Save(zipFileToCreate); } // open and lock using (new FileStream(zipFileToCreate, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)) { using (FileSystemZip.Read(zipFileToCreate)) { } } }
public void Error_Read_InvalidZip() { string filename = zipit; // try reading the invalid zipfile - this must fail. using (ZipFile zip = FileSystemZip.Read(filename)) { foreach (ZipEntry e in zip) { System.Console.WriteLine("name: {0} compressed: {1} has password?: {2}", e.FileName, e.CompressedSize, e.UsesEncryption); } } }
[ExpectedException(typeof(ZipException))] // not sure which exception - could be one of several. public void Error_ReadCorruptedZipFile() { int i; string zipFileToCreate = Path.Combine(TopLevelDir, "Read_CorruptedZipFile.zip"); Directory.SetCurrentDirectory(TopLevelDir); // the list of filenames to add to the zip string[] filenames = { Path.Combine(SourceDir, "Tools", TestUtilities.GetBinDir("Zipit"), "Zipit.exe"), Path.Combine(SourceDir, "Tools", TestUtilities.GetBinDir("Unzip"), "Unzip.exe"), Path.Combine(SourceDir, TestUtilities.GetBinDir("Zip.Portable"), "Zip.Portable.xml"), Path.Combine(SourceDir, "Tools", "WinFormsApp", "Icon2.res"), }; // create the zipfile, adding the files using (ZipFile zip = new ZipFile()) { for (i = 0; i < filenames.Length; i++) { zip.AddFile(filenames[i], ""); } zip.Save(zipFileToCreate); } // now corrupt the zip archive IntroduceCorruption(zipFileToCreate); try { // read the corrupted zip - this should fail in some way using (ZipFile zip = FileSystemZip.Read(zipFileToCreate)) { foreach (var e in zip) { System.Console.WriteLine("name: {0} compressed: {1} has password?: {2}", e.FileName, e.CompressedSize, e.UsesEncryption); e.Extract("extract"); } } } catch (Exception exc1) { throw new ZipException("expected", exc1); } }
internal static int CountEntries(string zipfile) { int entries = 0; using (ZipFile zip = FileSystemZip.Read(zipfile)) { foreach (ZipEntry e in zip) { if (!e.IsDirectory) { entries++; } } } return(entries); }
private void _Internal_ExtractExisting(int flavor) { string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("Error-Extract-ExistingFileWithoutOverwrite-{0}.zip", flavor)); string resourceDir = Path.Combine(SourceDir, TestUtilities.GetBinDir("Zip.Portable.Tests"), "Resources"); Assert.IsTrue(Directory.Exists(resourceDir)); Directory.SetCurrentDirectory(TopLevelDir); var filenames = Directory.GetFiles(resourceDir); using (ZipFile zip = new ZipFile()) { zip.AddFiles(filenames, ""); zip.Comment = "This is a Comment On the Archive"; zip.Save(zipFileToCreate); } Assert.AreEqual <int>(TestUtilities.CountEntries(zipFileToCreate), filenames.Length, "The zip file created has the wrong number of entries."); // Extract twice: the first time should succeed. // The second, should fail, because of a failed file overwrite. // Unless flavor==3, in which case we overwrite silently. for (int k = 0; k < 2; k++) { using (ZipFile zip = FileSystemZip.Read(zipFileToCreate)) { if (flavor > 10) { zip.ExtractProgress += OverwriteDecider; } for (int j = 0; j < filenames.Length; j++) { ZipEntry e = zip[Path.GetFileName(filenames[j])]; if (flavor == 4) { e.Extract("unpack"); } else { e.Extract("unpack", (ExtractExistingFileAction)flavor); } } } } }
public void Error_EmptySplitZip() { string zipFileToCreate = "zftc.zip"; using (var zip = new ZipFile()) { zip.MaxOutputSegmentSize = 1024 * 1024; zip.Save(zipFileToCreate); } string extractDir = "extract"; using (var zip = FileSystemZip.Read(zipFileToCreate)) { zip.ExtractAll(extractDir); Assert.IsTrue(zip.Entries.Count == 0); } }
public void WZA_MacCheck_ZeroLengthEntry_wi13892() { if (!WinZipIsPresent) { throw new Exception("no winzip!"); } // This zipfile has some zero-length entries. Previously // DotNetZip was throwing a spurious MAC mismatch error on // those zero-length entries. string baseFileName = "wi13892.zip"; string extractDir = "extract"; string password = "******"; string sourceDir = CurrentDir; for (int i = 0; i < 3; i++) { sourceDir = Path.GetDirectoryName(sourceDir); } string fqFileName = Path.Combine(Path.Combine(sourceDir, "Zip Tests\\bin\\Debug\\zips"), baseFileName); TestContext.WriteLine("Reading zip file: '{0}'", fqFileName); using (ZipFile zip = FileSystemZip.Read(fqFileName)) { zip.Password = password; foreach (ZipEntry e in zip) { TestContext.WriteLine("{1,-22} {2,9} {3,5:F0}% {4,9} {5,3} {6:X8} {0}", e.FileName, e.LastModified.ToString("yyyy-MM-dd HH:mm:ss"), e.UncompressedSize, e.CompressionRatio, e.CompressedSize, (e.UsesEncryption) ? "Y" : "N", e.Crc); e.Extract(extractDir); } } }
public void Password_Extract_WrongPassword() { string ZipFileToCreate = Path.Combine(TopLevelDir, "MultipleEntriesDifferentPasswords.zip"); Assert.IsFalse(File.Exists(ZipFileToCreate), "The temporary zip file '{0}' already exists.", ZipFileToCreate); Directory.SetCurrentDirectory(TopLevelDir); string[] filenames = { Path.Combine(SourceDir, "Tools", TestUtilities.GetBinDir("Zipit"), "Zipit.exe"), Path.Combine(SourceDir, TestUtilities.GetBinDir("Zip.Portable"), "Zip.Portable.xml"), }; string[] passwords = { "12345678", "0987654321", }; int j = 0; using (ZipFile zip = new ZipFile()) { for (j = 0; j < filenames.Length; j++) { zip.Password = passwords[j]; zip.AddFile(filenames[j], ""); } zip.Save(ZipFileToCreate); } // now try to extract using (ZipFile zip = FileSystemZip.Read(ZipFileToCreate)) { for (j = 0; j < filenames.Length; j++) { zip[Path.GetFileName(filenames[j])].ExtractWithPassword("unpack", ExtractExistingFileAction.OverwriteSilently, "WrongPassword"); } } }
public void Error_AddFile_Twice() { int i; // select the name of the zip file string zipFileToCreate = Path.Combine(TopLevelDir, "Error_AddFile_Twice.zip"); // create the subdirectory string subdir = Path.Combine(TopLevelDir, "files"); Directory.CreateDirectory(subdir); // create a bunch of files int numFilesToCreate = _rnd.Next(23) + 14; for (i = 0; i < numFilesToCreate; i++) { TestUtilities.CreateUniqueFile("bin", subdir, _rnd.Next(10000) + 5000); } // Create the zip archive Directory.SetCurrentDirectory(TopLevelDir); using (ZipFile zip1 = new ZipFile()) { zip1.StatusMessageTextWriter = System.Console.Out; string[] files = Directory.GetFiles(subdir); zip1.AddFiles(files, "files"); zip1.Save(zipFileToCreate); } // this should fail - adding the same file twice using (ZipFile zip2 = FileSystemZip.Read(zipFileToCreate)) { zip2.StatusMessageTextWriter = System.Console.Out; string[] files = Directory.GetFiles(subdir); for (i = 0; i < files.Length; i++) { zip2.AddFile(files[i], "files"); } zip2.Save(zipFileToCreate); } }
public void Password_CheckBadPassword_wi13668() { TestContext.WriteLine("Password_CheckBadPassword_wi13668()"); // In this case, the password is "correct" but the decrypted // header does not match the CRC. Therefore the library // should fail this password. I don't know how the zip was // constructed but I suspect a broken library. string fileName = _GetNameForZipContentFile("wi13668-bad-pwd-472713.zip"); string password = "******"; TestContext.WriteLine("Reading zip file: '{0}'", fileName); using (ZipFile zip = FileSystemZip.Read(fileName)) { foreach (ZipEntry e in zip) { // will throw if wrong password e.ExtractWithPassword(Stream.Null, password); } } }
public static void Main(String[] args) { int startArgs = 0; int i; int codePage = 0; string zipfile = null; string targdir = null; string password = null; List <string> entriesToExtract = new List <String>(); bool extractToConsole = false; ActionDesired action = ActionDesired.Extract; ExtractExistingFileAction behaviorForExistingFile = ExtractExistingFileAction.DoNotOverwrite; bool wantQuiet = false; bool wantFlatten = false; System.IO.Stream bitbucket = System.IO.Stream.Null; System.IO.Stream outstream = null; // because the comments and filenames on zip entries may be UTF-8 //System.Console.OutputEncoding = new System.Text.UTF8Encoding(); if (args.Length == 0) { Usage(); } if (args[0] == "-") { extractToConsole = true; outstream = Console.OpenStandardOutput(); startArgs = 1; } for (i = startArgs; i < args.Length; i++) { switch (args[i]) { case "-cp": i++; if (args.Length <= i) { Usage(); } if (codePage != 0) { Usage(); } System.Int32.TryParse(args[i], out codePage); break; case "-d": i++; if (args.Length <= i) { Usage(); } if (targdir != null) { Usage(); } if (extractToConsole) { Usage(); } if (action != ActionDesired.Extract) { Usage(); } targdir = args[i]; break; case "-f": wantFlatten = true; if (action != ActionDesired.Extract) { Usage(); } break; case "-i": if (password != null) { Usage(); } if (targdir != null) { Usage(); } if (wantQuiet) { Usage(); } if (entriesToExtract.Count > 0) { Usage(); } action = ActionDesired.Info; break; case "-l": if (password != null) { Usage(); } if (targdir != null) { Usage(); } if (wantQuiet) { Usage(); } if (entriesToExtract.Count > 0) { Usage(); } if (behaviorForExistingFile == ExtractExistingFileAction.OverwriteSilently) { Usage(); } action = ActionDesired.List; break; case "-o": behaviorForExistingFile = ExtractExistingFileAction.OverwriteSilently; if (action != ActionDesired.Extract) { Usage(); } break; case "-r": if (wantFlatten == true) { Usage(); } if (targdir != null) { Usage(); } if (action == ActionDesired.Test) { Usage(); } action = ActionDesired.Repair; break; case "-p": i++; if (args.Length <= i) { Usage(); } if (password != null) { Usage(); } password = args[i]; break; case "-q": if (action == ActionDesired.List) { Usage(); } wantQuiet = true; break; case "-t": action = ActionDesired.Test; if (targdir != null) { Usage(); } //if (wantQuiet) Usage(); if (entriesToExtract.Count > 0) { Usage(); } break; case "-?": Usage(); break; default: // positional args if (zipfile == null) { zipfile = args[i]; } else if (action != ActionDesired.Extract) { Usage(); } else { entriesToExtract.Add(args[i]); } break; } } if (zipfile == null) { Console.WriteLine("unzip: No zipfile specified.\n"); Usage(); } if (!System.IO.File.Exists(zipfile)) { Console.WriteLine("unzip: That zip file does not exist!\n"); Usage(); } if (targdir == null) { targdir = "."; } try { if (action == ActionDesired.Repair) { FileSystemZip.FixZipDirectory(zipfile); } else { var options = new ReadOptions { Encoding = (codePage != 0) ? System.Text.Encoding.GetEncoding(codePage) : null }; using (ZipFile zip = FileSystemZip.Read(zipfile, options)) { if (entriesToExtract.Count > 0) { // extract specified entries foreach (var entryToExtract in entriesToExtract) { // find the entry ZipEntry e = zip[entryToExtract]; if (e == null) { System.Console.WriteLine(" entry ({0}) does not exist in the zip archive.", entryToExtract); } else { if (wantFlatten) { e.FileName = System.IO.Path.GetFileName(e.FileName); } if (password == null) { if (e.UsesEncryption) { System.Console.WriteLine(" That entry ({0}) requires a password to extract.", entryToExtract); } else if (extractToConsole) { e.Extract(outstream); } else { e.Extract(targdir, behaviorForExistingFile); } } else { if (extractToConsole) { e.ExtractWithPassword(outstream, password); } else { e.ExtractWithPassword(targdir, behaviorForExistingFile, password); } } } } } else if (action == ActionDesired.Info) { System.Console.WriteLine("{0}", zip.Info); } else { // extract all, or list, or test // The logic here does almost the same thing as the ExtractAll() method // on the ZipFile class. But in this case we *could* have control over // it, for example only extract files of a certain type, or whose names // matched a certain pattern, or whose lastmodified times fit a certain // condition, or use a different password for each entry, etc. We can // also display status for each entry, as here. Int64 totalUncompressedSize = 0; bool header = true; foreach (ZipEntry e in zip.EntriesSorted) { if (!wantQuiet) { if (header) { System.Console.WriteLine("Zipfile: {0}", zip.Name); if ((zip.Comment != null) && (zip.Comment != "")) { System.Console.WriteLine("Comment: {0}", zip.Comment); } System.Console.WriteLine("\n{1,-22} {2,10} {3,5} {4,10} {5,3} {6,8} {0}", "Filename", "Modified", "Size", "Ratio", "Packed", "pw?", "CRC"); System.Console.WriteLine(new System.String('-', 80)); header = false; } totalUncompressedSize += e.UncompressedSize; System.Console.WriteLine("{1,-22} {2,10} {3,5:F0}% {4,10} {5,3} {6:X8} {0}", e.FileName, e.LastModified.ToString("yyyy-MM-dd HH:mm:ss"), e.UncompressedSize, e.CompressionRatio, e.CompressedSize, (e.UsesEncryption) ? "Y" : "N", e.Crc); if ((e.Comment != null) && (e.Comment != "")) { System.Console.WriteLine(" Comment: {0}", e.Comment); } } if (action == ActionDesired.Extract) { if (e.UsesEncryption) { if (password == null) { System.Console.WriteLine("unzip: {0}: Cannot extract this entry without a password.", e.FileName); } else { if (wantFlatten) { e.FileName = System.IO.Path.GetFileName(e.FileName); } if (extractToConsole) { e.ExtractWithPassword(outstream, password); } else { e.ExtractWithPassword(targdir, behaviorForExistingFile, password); } } } else { if (wantFlatten) { e.FileName = System.IO.Path.GetFileName(e.FileName); } if (extractToConsole) { e.Extract(outstream); } else { e.Extract(targdir, behaviorForExistingFile); } } } else if (action == ActionDesired.Test) { e.ExtractWithPassword(bitbucket, password); } } // foreach if (!wantQuiet) { System.Console.WriteLine(new System.String('-', 80)); System.Console.WriteLine("{1,-22} {2,10} {3,5} {4,10} {5,3} {6,8} {0}", zip.Entries.Count.ToString() + " files", "", totalUncompressedSize, "", "", "", ""); } } // else (extract all) } // end using(), the underlying file is closed. } } catch (System.Exception ex1) { System.Console.Error.WriteLine("exception: " + ex1); } Console.WriteLine(); }
public void SilentDeletion_wi10639() { string zipFileToCreate = "SilentDeletion.zip"; string dirToZip = "dirToZip"; string extractDir = "extracted"; string password = TestUtilities.GenerateRandomPassword(); string wrongPassword = "******"; var files = TestUtilities.GenerateFilesFlat(dirToZip); TestContext.WriteLine("Creating the zip."); using (var zip = new ZipFile()) { zip.Password = password; zip.AddFiles(files, dirToZip); zip.Save(zipFileToCreate); } TestContext.WriteLine("Extract one file with wrong password."); // pick a random entry to extract int ix = -1; string extractedFile = null; // perform two passes: first with correct password to extract the // file. 2nd with incorrect password to see if the file is // deleted. Directory.CreateDirectory(extractDir); for (int i = 0; i < 2; i++) { try { using (var zip = FileSystemZip.Read(zipFileToCreate)) { if (i == 0) { do { ix = this._rnd.Next(zip.Entries.Count); }while (zip[ix].IsDirectory); TestContext.WriteLine("Selected entry: {0}", zip[ix].FileName); extractedFile = Path.Combine(extractDir, zip[ix].FileName.Replace('/', Path.DirectorySeparatorChar)); TestContext.WriteLine("name for extracted file: {0}", extractedFile); Assert.IsFalse(File.Exists(extractedFile), "The file exists."); } TestContext.WriteLine("Cycle {0}: ExtractWithPassword()", i); zip[ix].ExtractWithPassword(extractDir, ExtractExistingFileAction.OverwriteSilently, (i == 0)? password : wrongPassword); } } catch (BadPasswordException) { // only swallow exceptions on the first go-round if (i == 0) { throw; } } Assert.IsTrue(File.Exists(extractedFile), "Cycle {0}: The extracted file does not exist.", i); } }
public void Password_BasicAddAndExtract() { int i; string[] Passwords = { null, "Password!", TestUtilities.GenerateRandomPassword(), "A" }; Ionic.Zlib.CompressionLevel[] compressionLevelOptions = { Ionic.Zlib.CompressionLevel.None, Ionic.Zlib.CompressionLevel.BestSpeed, Ionic.Zlib.CompressionLevel.Default, Ionic.Zlib.CompressionLevel.BestCompression, }; for (int k = 0; k < compressionLevelOptions.Length; k++) { for (int j = 0; j < Passwords.Length; j++) { TestContext.WriteLine("\n\n===================\nTrial ({0}) pw({1})", j, Passwords[j]); string ZipFileToCreate = Path.Combine(TopLevelDir, String.Format("Password_BasicAddAndExtract-{0}-{1}.zip", k, j)); Assert.IsFalse(File.Exists(ZipFileToCreate), "The temporary zip file '{0}' already exists.", ZipFileToCreate); Directory.SetCurrentDirectory(TopLevelDir); string DirToZip = String.Format("zipthis-{0}-{1}", k, j); Directory.CreateDirectory(DirToZip); TestContext.WriteLine("\n---------------------creating files and computing checksums..."); int NumFilesToCreate = _rnd.Next(10) + 10; string[] filenames = new string[NumFilesToCreate]; var checksums = new Dictionary <string, string>(); for (i = 0; i < NumFilesToCreate; i++) { filenames[i] = Path.Combine(DirToZip, String.Format("file{0:D3}.txt", i)); int sz = _rnd.Next(22000) + 3000; //int sz = 1000; var repeatedLine = String.Format("Line to Repeat... {0} {1} {2} filename: {3}", i, k, j, filenames[i]); TestUtilities.CreateAndFillFileText(filenames[i], repeatedLine, sz); string key = Path.GetFileName(filenames[i]); checksums.Add(key, TestUtilities.GetCheckSumString(filenames[i])); TestContext.WriteLine(" chk[{0}]={1}", key, checksums[key]); } TestContext.WriteLine("\n---------------------adding files to the archive..."); var sw = new StringWriter(); using (ZipFile zip = new ZipFile()) { zip.StatusMessageTextWriter = sw; zip.CompressionLevel = compressionLevelOptions[k]; zip.Password = Passwords[j]; zip.AddDirectory(Path.GetFileName(DirToZip)); zip.Save(ZipFileToCreate); } TestContext.WriteLine(sw.ToString()); Assert.AreEqual <int>(TestUtilities.CountEntries(ZipFileToCreate), NumFilesToCreate, "The Zip file has an unexpected number of entries."); TestContext.WriteLine("\n---------------------verifying checksums..."); using (ZipFile zip = FileSystemZip.Read(ZipFileToCreate)) { foreach (ZipEntry e in zip) { TestContext.WriteLine("found entry: {0}", e.FileName); } var extractDir = String.Format("extract-{0}-{1}", k, j); TestContext.WriteLine(" Extract with pw({0})", Passwords[j]); foreach (ZipEntry e in zip) { e.ExtractWithPassword(extractDir, ExtractExistingFileAction.OverwriteSilently, Passwords[j]); if (!e.IsDirectory) { byte[] c2 = TestUtilities.ComputeChecksum(Path.Combine(extractDir, e.FileName)); Assert.AreEqual <string>(checksums[e.FileName], TestUtilities.CheckSumToString(c2), "The checksum of the extracted file is incorrect."); } } } TestContext.WriteLine("\n"); } } }
public void Password_AddEntryWithPasswordToExistingZip() { string zipFileToCreate = "AddEntryWithPasswordToExistingZip.zip"; string[] filenames = { Path.Combine(SourceDir, "Tools", TestUtilities.GetBinDir("Zipit"), "Zipit.exe"), Path.Combine(SourceDir, TestUtilities.GetBinDir("Zip.Portable"), "Zip.Portable.xml"), }; string[] checksums = { TestUtilities.GetCheckSumString(filenames[0]), TestUtilities.GetCheckSumString(filenames[1]), }; int j = 0; using (ZipFile zip = new ZipFile()) { for (j = 0; j < filenames.Length; j++) { zip.AddFile(filenames[j], ""); } zip.Save(zipFileToCreate); } Assert.AreEqual <int>(TestUtilities.CountEntries(zipFileToCreate), 2, "wrong number of entries."); string fileX = Path.Combine(SourceDir, "Tools", TestUtilities.GetBinDir("Unzip"), "unzip.exe"); string checksumX = TestUtilities.GetCheckSumString(fileX); string password = TestUtilities.GenerateRandomPassword() + "!"; using (ZipFile zip = FileSystemZip.Read(zipFileToCreate)) { zip.Password = password; zip.AddFile(fileX, ""); zip.Save(zipFileToCreate); } Assert.AreEqual <int>(TestUtilities.CountEntries(zipFileToCreate), 3, "wrong number of entries."); string unpackDir = "unpack"; string newpath, chk, baseName; using (ZipFile zip = FileSystemZip.Read(zipFileToCreate)) { for (j = 0; j < filenames.Length; j++) { baseName = Path.GetFileName(filenames[j]); zip[baseName].Extract(unpackDir, ExtractExistingFileAction.OverwriteSilently); newpath = Path.Combine(unpackDir, filenames[j]); chk = TestUtilities.GetCheckSumString(newpath); Assert.AreEqual <string>(checksums[j], chk, "Checksums do not match."); } baseName = Path.GetFileName(fileX); zip[baseName].ExtractWithPassword(unpackDir, ExtractExistingFileAction.OverwriteSilently, password); newpath = Path.Combine(unpackDir, fileX); chk = TestUtilities.GetCheckSumString(newpath); Assert.AreEqual <string>(checksumX, chk, "Checksums do not match."); } }
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 = FileSystemZip.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 Unicode_AddDirectoryByName_wi8984() { string format = "弹出应用程序{0:D3}.dir"; // Chinese characters System.Text.Encoding UTF8 = System.Text.Encoding.GetEncoding("UTF-8"); TestContext.WriteLine("== WorkItem 8984"); // three trials: one for old-style // ProvisionalAlternateEncoding, one for "AsNecessary" // and one for "Always" for (int j = 0; j < 3; j++) { TestContext.WriteLine("Trial {0}", j); for (int n = 1; n <= 10; n++) { TestContext.WriteLine("nEntries {0}", n); var dirsAdded = new System.Collections.Generic.List <String>(); var zipFileToCreate = String.Format("wi8984-{0}-{1:N2}.zip", j, n); using (ZipFile zip1 = new ZipFile()) { switch (j) { case 0: #pragma warning disable 618 zip1.UseUnicodeAsNecessary = true; #pragma warning restore 618 break; case 1: zip1.AlternateEncoding = UTF8; zip1.AlternateEncodingUsage = ZipOption.AsNecessary; break; case 2: zip1.AlternateEncoding = UTF8; zip1.AlternateEncodingUsage = ZipOption.Always; break; } for (int i = 0; i < n; i++) { // create an arbitrary directory name, add it to the zip archive string dirName = String.Format(format, i); zip1.AddDirectoryByName(dirName); dirsAdded.Add(dirName + "/"); } zip1.Save(zipFileToCreate); } string extractDir = String.Format("extract-{0}-{1:D3}", j, n); int dirCount = 0; using (ZipFile zip2 = FileSystemZip.Read(zipFileToCreate)) { foreach (var e in zip2) { TestContext.WriteLine("dir: {0}", e.FileName); Assert.IsTrue(dirsAdded.Contains(e.FileName), "Cannot find the expected entry ({0})", e.FileName); Assert.IsTrue(e.IsDirectory); e.Extract(extractDir); dirCount++; } } Assert.AreEqual <int>(n, dirCount); TestContext.WriteLine(""); } TestContext.WriteLine(""); } }