TestArchive() public method

Test an archive for integrity/validity
Testing will terminate on the first error found.
public TestArchive ( bool testData ) : bool
testData bool Perform low level data Crc check
return bool
Example #1
2
        void TryDeleting(byte[] master, int totalEntries, int additions, params int[] toDelete)
        {
            MemoryStream ms = new MemoryStream();
            ms.Write(master, 0, master.Length);

            using (ZipFile f = new ZipFile(ms)) {
                f.IsStreamOwner = false;
                Assert.AreEqual(totalEntries, f.Count);
                Assert.IsTrue(f.TestArchive(true));
                f.BeginUpdate(new MemoryArchiveStorage());

                for (int i = 0; i < additions; ++i) {
                    f.Add(new StringMemoryDataSource("Another great file"),
                        string.Format("Add{0}.dat", i + 1));
                }

                foreach (int i in toDelete) {
                    f.Delete(f[i]);
                }
                f.CommitUpdate();

                /* write stream to file to assist debugging.
                                byte[] data = ms.ToArray();
                                using ( FileStream fs = File.Open(@"c:\aha.zip", FileMode.Create, FileAccess.ReadWrite, FileShare.Read) ) {
                                    fs.Write(data, 0, data.Length);
                                }
                */
                int newTotal = totalEntries + additions - toDelete.Length;
                Assert.AreEqual(newTotal, f.Count,
                    string.Format("Expected {0} entries after update found {1}", newTotal, f.Count));
                Assert.IsTrue(f.TestArchive(true), "Archive test should pass");
            }
        }
Example #2
0
        public void Basics()
        {
            const string tempName1 = "a(1).dat";

            MemoryStream target = new MemoryStream();

            string tempFilePath = GetTempFilePath();
            Assert.IsNotNull(tempFilePath, "No permission to execute this test?");

            string addFile = Path.Combine(tempFilePath, tempName1);
            MakeTempFile(addFile, 1);

            try {
                FastZip fastZip = new FastZip();
                fastZip.CreateZip(target, tempFilePath, false, @"a\(1\)\.dat", null);

                MemoryStream archive = new MemoryStream(target.ToArray());
                using (ZipFile zf = new ZipFile(archive)) {
                    Assert.AreEqual(1, zf.Count);
                    ZipEntry entry = zf[0];
                    Assert.AreEqual(tempName1, entry.Name);
                    Assert.AreEqual(1, entry.Size);
                    Assert.IsTrue(zf.TestArchive(true));

                    zf.Close();
                }
            }
            finally {
                File.Delete(tempName1);
            }
        }
Example #3
0
 /// <summary>
 /// Tests the archive.
 /// </summary>
 /// <param name="data">The data.</param>
 /// <param name="password">The password.</param>
 /// <returns>true if archive tests ok; false otherwise.</returns>
 public static bool TestArchive(byte[] data, string password)
 {
     using (MemoryStream ms = new MemoryStream(data))
     using (ZipFile zipFile = new ZipFile(ms)) {
         zipFile.Password = password;
         return zipFile.TestArchive(true);
     }
 }
Example #4
0
 /// <summary>
 /// Tests the archive.
 /// </summary>
 /// <param name="data">The data.</param>
 /// <param name="password">The password.</param>
 /// <returns>true if archive tests ok; false otherwise.</returns>
 public static bool TestArchive(byte[] data, string password)
 {
     using (MemoryStream ms = new MemoryStream(data))
         using (ZipFile zipFile = new ZipFile(ms))
         {
             zipFile.Password = password;
             return(zipFile.TestArchive(true));
         }
 }
		/// <summary>
		/// Tests the archive.
		/// </summary>
		/// <param name="data">The data.</param>
		/// <param name="password">The password.</param>
		/// <returns>true if archive tests ok; false otherwise.</returns>
		public static bool TestArchive(byte[] data, string password)
		{
			using (MemoryStream ms = new MemoryStream(data))
			using (ZipFile zipFile = new ZipFile(ms)) {
#if !PCL
				zipFile.Password = password;
#else
                if (!String.IsNullOrWhiteSpace(password))
                    throw new InvalidOperationException("Password not supported in PCL");
#endif
				return zipFile.TestArchive(true);
			}
		}
Example #6
0
        public void Extract(string compressedFile, string destination)
        {
            _logger.Trace("Extracting archive [{0}] to [{1}]", compressedFile, destination);

            using (var fileStream = File.OpenRead(compressedFile))
            {
                var zipFile = new ZipFile(fileStream);

                _logger.Debug("Validating Archive {0}", compressedFile);

                if (!zipFile.TestArchive(true, TestStrategy.FindFirstError, OnZipError))
                {
                    throw new IOException(string.Format("File {0} failed archive validation.", compressedFile));
                }

                foreach (ZipEntry zipEntry in zipFile)
                {
                    if (!zipEntry.IsFile)
                    {
                        continue; // Ignore directories
                    }
                    String entryFileName = zipEntry.Name;
                    // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
                    // Optionally match entrynames against a selection list here to skip as desired.
                    // The unpacked length is available in the zipEntry.Size property.

                    byte[] buffer = new byte[4096]; // 4K is optimum
                    Stream zipStream = zipFile.GetInputStream(zipEntry);

                    // Manipulate the output filename here as desired.
                    String fullZipToPath = Path.Combine(destination, entryFileName);
                    string directoryName = Path.GetDirectoryName(fullZipToPath);
                    if (directoryName.Length > 0)
                        Directory.CreateDirectory(directoryName);

                    // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
                    // of the file, but does not waste memory.
                    // The "using" will close the stream even if an exception occurs.
                    using (FileStream streamWriter = File.Create(fullZipToPath))
                    {
                        StreamUtils.Copy(zipStream, streamWriter, buffer);
                    }
                }
            }

            _logger.Trace("Extraction complete.");
        }
Example #7
0
        public static void unzipFromStream(Stream fileStream, string outFolder)
        {
            ZipConstants.DefaultCodePage = 850;//force the use of this codepage to unzip. Multilingual (Latin-1) (Western European languages)
            ZipFile zipFile = new ZipFile(fileStream);
            if (zipFile.TestArchive(true))
            {
                try
                {
                    foreach (ZipEntry e in zipFile)
                    {

                        String entryFileName = e.Name;
                        byte[] buffer = new byte[4096];
                        Stream zipStream = zipFile.GetInputStream(e);

                        String fullZipToPath = Path.Combine(outFolder, entryFileName);
                        string directoryName = Path.GetDirectoryName(fullZipToPath);
                        if (directoryName.Length > 0)
                            Directory.CreateDirectory(directoryName);

                        if (Path.GetFileName(fullZipToPath) != String.Empty)
                        {
                            using (FileStream streamWriter = File.Create(fullZipToPath))
                            {
                                StreamUtils.Copy(zipStream, streamWriter, buffer);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    try
                    {
                        if (Directory.Exists(outFolder))
                        {
                            Directory.Delete(outFolder);
                        }
                    }
                    catch { }
                    throw e;
                }
            }
            else
            {
                throw new Exception("Zip file not valid.");
            }
        }
Example #8
0
        public void NameFactory()
        {
            MemoryStream memStream = new MemoryStream();
            DateTime fixedTime = new DateTime(1981, 4, 3);
            using (ZipFile f = new ZipFile(memStream))
            {
                f.IsStreamOwner = false;
                ((ZipEntryFactory)f.EntryFactory).IsUnicodeText = true;
                ((ZipEntryFactory)f.EntryFactory).Setting = ZipEntryFactory.TimeSetting.Fixed;
                ((ZipEntryFactory)f.EntryFactory).FixedDateTime = fixedTime;
                ((ZipEntryFactory)f.EntryFactory).SetAttributes = 1;
                f.BeginUpdate(new MemoryArchiveStorage());

                string[] names = new string[]
                {
                    "\u030A\u03B0",     // Greek
                    "\u0680\u0685",     // Arabic
                };

                foreach (string name in names)
                {
                    f.Add(new StringMemoryDataSource("Hello world"), name,
                          CompressionMethod.Deflated, true);
                }
                f.CommitUpdate();
                Assert.IsTrue(f.TestArchive(true));

                foreach (string name in names)
                {
                    int index = f.FindEntry(name, true);

                    Assert.IsTrue(index >= 0);
                    ZipEntry found = f[index];
                    Assert.AreEqual(name, found.Name);
                    Assert.IsTrue(found.IsUnicodeText);
                    Assert.AreEqual(fixedTime, found.DateTime);
                    Assert.IsTrue(found.IsDOSEntry);
                }
            }
        }
Example #9
0
        public void Crypto_AddEncryptedEntryToExistingArchiveSafe()
        {
            MemoryStream ms = new MemoryStream();

            byte[] rawData;

            using (ZipFile testFile = new ZipFile(ms))
            {
                testFile.IsStreamOwner = false;
                testFile.BeginUpdate();
                testFile.Add(new StringMemoryDataSource("Aha"), "No1", CompressionMethod.Stored);
                testFile.Add(new StringMemoryDataSource("And so it goes"), "No2", CompressionMethod.Stored);
                testFile.Add(new StringMemoryDataSource("No3"), "No3", CompressionMethod.Stored);
                testFile.CommitUpdate();

                Assert.IsTrue(testFile.TestArchive(true));
                rawData = ms.ToArray();
            }

            ms = new MemoryStream(rawData);

            using (ZipFile testFile = new ZipFile(ms))
            {
                Assert.IsTrue(testFile.TestArchive(true));

                testFile.BeginUpdate(new MemoryArchiveStorage(FileUpdateMode.Safe));
                testFile.Password = "******";
                testFile.Add(new StringMemoryDataSource("Zapata!"), "encrypttest.xml");
                testFile.CommitUpdate();

                Assert.IsTrue(testFile.TestArchive(true));

                int entryIndex = testFile.FindEntry("encrypttest.xml", true);
                Assert.IsNotNull(entryIndex >= 0);
                Assert.IsTrue(testFile[entryIndex].IsCrypted);
            }
        }
Example #10
0
        public void Zip64Descriptor()
        {
            MemoryStream msw = new MemoryStreamWithoutSeek();
            ZipOutputStream outStream = new ZipOutputStream(msw);
            outStream.UseZip64 = UseZip64.Off;

            outStream.IsStreamOwner = false;
            outStream.PutNextEntry(new ZipEntry("StripedMarlin"));
            outStream.WriteByte(89);
            outStream.Close();

            MemoryStream ms = new MemoryStream(msw.ToArray());
            using (ZipFile zf = new ZipFile(ms))
            {
                Assert.IsTrue(zf.TestArchive(true));
            }

            msw = new MemoryStreamWithoutSeek();
            outStream = new ZipOutputStream(msw);
            outStream.UseZip64 = UseZip64.On;

            outStream.IsStreamOwner = false;
            outStream.PutNextEntry(new ZipEntry("StripedMarlin"));
            outStream.WriteByte(89);
            outStream.Close();

            ms = new MemoryStream(msw.ToArray());
            using (ZipFile zf = new ZipFile(ms))
            {
                Assert.IsTrue(zf.TestArchive(true));
            }
        }
Example #11
0
        public void Zip64Useage()
        {
            MemoryStream memStream = new MemoryStream();
            using (ZipFile f = new ZipFile(memStream)) {
                f.IsStreamOwner = false;
                f.UseZip64 = UseZip64.On;

                StringMemoryDataSource m = new StringMemoryDataSource("0000000");
                f.BeginUpdate(new MemoryArchiveStorage());
                f.Add(m, "a.dat");
                f.Add(m, "b.dat");
                f.CommitUpdate();
                Assert.IsTrue(f.TestArchive(true));
            }

            byte[] rawArchive = memStream.ToArray();

            byte[] pseudoSfx = new byte[1049 + rawArchive.Length];
            Array.Copy(rawArchive, 0, pseudoSfx, 1049, rawArchive.Length);

            memStream = new MemoryStream(pseudoSfx);
            using (ZipFile f = new ZipFile(memStream)) {
                for (int index = 0; index < f.Count; ++index) {
                    Stream entryStream = f.GetInputStream(index);
                    MemoryStream data = new MemoryStream();
                    StreamUtils.Copy(entryStream, data, new byte[128]);
                    string contents = Encoding.ASCII.GetString(data.ToArray());
                    Assert.AreEqual("0000000", contents);
                }
            }
        }
Example #12
0
        public void UpdateCommentOnlyInMemory()
        {
            MemoryStream ms = new MemoryStream();

            using (ZipFile testFile = new ZipFile(ms))
            {
                testFile.IsStreamOwner = false;
                testFile.BeginUpdate();
                testFile.Add(new StringMemoryDataSource("Aha"), "No1", CompressionMethod.Stored);
                testFile.Add(new StringMemoryDataSource("And so it goes"), "No2", CompressionMethod.Stored);
                testFile.Add(new StringMemoryDataSource("No3"), "No3", CompressionMethod.Stored);
                testFile.CommitUpdate();

                Assert.IsTrue(testFile.TestArchive(true));
            }

            using (ZipFile testFile = new ZipFile(ms))
            {
                Assert.IsTrue(testFile.TestArchive(true));
                Assert.AreEqual("", testFile.ZipFileComment);
                testFile.IsStreamOwner = false;

                testFile.BeginUpdate();
                testFile.SetComment("Here is my comment");
                testFile.CommitUpdate();

                Assert.IsTrue(testFile.TestArchive(true));
            }

            using (ZipFile testFile = new ZipFile(ms))
            {
                Assert.IsTrue(testFile.TestArchive(true));
                Assert.AreEqual("Here is my comment", testFile.ZipFileComment);
            }
        }
Example #13
0
        public void AddEncryptedEntriesToExistingArchive()
        {
            const string TestValue = "0001000";
            MemoryStream memStream = new MemoryStream();
            using (ZipFile f = new ZipFile(memStream)) {
                f.IsStreamOwner = false;
                f.UseZip64 = UseZip64.Off;

                StringMemoryDataSource m = new StringMemoryDataSource(TestValue);
                f.BeginUpdate(new MemoryArchiveStorage());
                f.Add(m, "a.dat");
                f.CommitUpdate();
                Assert.IsTrue(f.TestArchive(true), "Archive test should pass");
            }

            using (ZipFile g = new ZipFile(memStream)) {
                ZipEntry ze = g[0];

                Assert.IsFalse(ze.IsCrypted, "Entry should NOT be encrypted");
                using (StreamReader r = new StreamReader(g.GetInputStream(0))) {
                    string data = r.ReadToEnd();
                    Assert.AreEqual(TestValue, data);
                }

                StringMemoryDataSource n = new StringMemoryDataSource(TestValue);

                g.Password = "******";
                g.UseZip64 = UseZip64.Off;
                g.IsStreamOwner = false;
                g.BeginUpdate();
                g.Add(n, "a1.dat");
                g.CommitUpdate();
                Assert.IsTrue(g.TestArchive(true), "Archive test should pass");
                ze = g[1];
                Assert.IsTrue(ze.IsCrypted, "New entry should be encrypted");

                using (StreamReader r = new StreamReader(g.GetInputStream(0))) {
                    string data = r.ReadToEnd();
                    Assert.AreEqual(TestValue, data);
                }
            }
        }
Example #14
0
        public void AddAndDeleteEntriesMemory()
        {
            MemoryStream memStream = new MemoryStream();

            using (ZipFile f = new ZipFile(memStream)) {
                f.IsStreamOwner = false;

                f.BeginUpdate(new MemoryArchiveStorage());
                f.Add(new StringMemoryDataSource("Hello world"), @"z:\a\a.dat");
                f.Add(new StringMemoryDataSource("Another"), @"\b\b.dat");
                f.Add(new StringMemoryDataSource("Mr C"), @"c\c.dat");
                f.Add(new StringMemoryDataSource("Mrs D was a star"), @"d\d.dat");
                f.CommitUpdate();
                Assert.IsTrue(f.TestArchive(true));
            }

            byte[] master = memStream.ToArray();

            TryDeleting(master, 4, 1, @"z:\a\a.dat");
            TryDeleting(master, 4, 1, @"\a\a.dat");
            TryDeleting(master, 4, 1, @"a/a.dat");

            TryDeleting(master, 4, 0, 0);
            TryDeleting(master, 4, 0, 1);
            TryDeleting(master, 4, 0, 2);
            TryDeleting(master, 4, 0, 3);
            TryDeleting(master, 4, 0, 0, 1);
            TryDeleting(master, 4, 0, 0, 2);
            TryDeleting(master, 4, 0, 0, 3);
            TryDeleting(master, 4, 0, 1, 2);
            TryDeleting(master, 4, 0, 1, 3);
            TryDeleting(master, 4, 0, 2);

            TryDeleting(master, 4, 1, 0);
            TryDeleting(master, 4, 1, 1);
            TryDeleting(master, 4, 3, 2);
            TryDeleting(master, 4, 4, 3);
            TryDeleting(master, 4, 10, 0, 1);
            TryDeleting(master, 4, 10, 0, 2);
            TryDeleting(master, 4, 10, 0, 3);
            TryDeleting(master, 4, 20, 1, 2);
            TryDeleting(master, 4, 30, 1, 3);
            TryDeleting(master, 4, 40, 2);
        }
Example #15
0
        public void AddAndDeleteEntries()
        {
            string tempFile = GetTempFilePath();
            Assert.IsNotNull(tempFile, "No permission to execute this test?");

            string addFile = Path.Combine(tempFile, "a.dat");
            MakeTempFile(addFile, 1);

            string addFile2 = Path.Combine(tempFile, "b.dat");
            MakeTempFile(addFile2, 259);

            tempFile = Path.Combine(tempFile, "SharpZipTest.Zip");

            using (ZipFile f = ZipFile.Create(tempFile)) {
                f.BeginUpdate();
                f.Add(addFile);
                f.Add(addFile2);
                f.CommitUpdate();
                Assert.IsTrue(f.TestArchive(true));
            }

            using (ZipFile f = new ZipFile(tempFile)) {
                Assert.AreEqual(2, f.Count);
                Assert.IsTrue(f.TestArchive(true));
                f.BeginUpdate();
                f.Delete(f[0]);
                f.CommitUpdate();
                Assert.AreEqual(1, f.Count);
                Assert.IsTrue(f.TestArchive(true));
            }

            File.Delete(addFile);
            File.Delete(addFile2);
            File.Delete(tempFile);
        }
Example #16
0
        public void NonAsciiPasswords()
        {
            const string tempName1 = "a.dat";

            MemoryStream target = new MemoryStream();

            string tempFilePath = GetTempFilePath();
            Assert.IsNotNull(tempFilePath, "No permission to execute this test?");

            string addFile = Path.Combine(tempFilePath, tempName1);
            MakeTempFile(addFile, 1);

            string password = "******";
            try {
                FastZip fastZip = new FastZip();
                fastZip.Password = password;

                fastZip.CreateZip(target, tempFilePath, false, @"a\.dat", null);

                MemoryStream archive = new MemoryStream(target.ToArray());
                using (ZipFile zf = new ZipFile(archive)) {
                    zf.Password = password;
                    Assert.AreEqual(1, zf.Count);
                    ZipEntry entry = zf[0];
                    Assert.AreEqual(tempName1, entry.Name);
                    Assert.AreEqual(1, entry.Size);
                    Assert.IsTrue(zf.TestArchive(true));
                    Assert.IsTrue(entry.IsCrypted);
                }
            }
            finally {
                File.Delete(tempName1);
            }
        }
Example #17
0
		/// <summary>
		/// Test an archive to see if its valid.
		/// </summary>
		/// <param name="fileSpecs">The files to test.</param>
		void Test(ArrayList fileSpecs)
		{
			string zipFileName = fileSpecs[0] as string;
			if (Path.GetExtension(zipFileName).Length == 0) 
			{
				zipFileName = Path.ChangeExtension(zipFileName, ".zip");
			}

			try
			{
				using (ZipFile zipFile = new ZipFile(zipFileName))
				{
					zipFile.Password = password_;
					if ( zipFile.TestArchive(testData_, TestStrategy.FindAllErrors,
						new ZipTestResultHandler(TestResultHandler)) )
					{
						Console.Out.WriteLine("Archive test passed");
					}
					else
					{
						Console.Out.WriteLine("Archive test failure");
					}
				}
			}
			catch(Exception ex)
			{
				Console.Out.WriteLine("Error list files - '{0}'", ex.Message);
			}
		}
Example #18
0
        bool CheckFile()
        {
            if (File.Exists(FileLoc))
            {
                try
                {
                    ZipFile zipFile = new ZipFile(FileLoc);
                    bool v = zipFile.TestArchive(false);
                    // Must call BeginUpdate to start, and CommitUpdate at the end.
                    //zipFile.BeginUpdate();
                    zipFile.Close();

                    return v;
                }
                catch (Exception e)
                {
                    logger.Exception(e, "CheckArchive", "zip corrupted: {0}", FileLoc);
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
Example #19
0
        public void NestedArchive()
        {
            MemoryStream ms = new MemoryStream();
            using (ZipOutputStream zos = new ZipOutputStream(ms)) {
                zos.IsStreamOwner = false;
                ZipEntry ze = new ZipEntry("Nest1");

                zos.PutNextEntry(ze);
                byte[] toWrite = Encoding.ASCII.GetBytes("Hello");
                zos.Write(toWrite, 0, toWrite.Length);
            }

            byte[] data = ms.ToArray();

            ms = new MemoryStream();
            using (ZipOutputStream zos = new ZipOutputStream(ms)) {
                zos.IsStreamOwner = false;
                ZipEntry ze = new ZipEntry("Container");
                ze.CompressionMethod = CompressionMethod.Stored;
                zos.PutNextEntry(ze);
                zos.Write(data, 0, data.Length);
            }

            using (ZipFile zipFile = new ZipFile(ms)) {
                ZipEntry e = zipFile[0];
                Assert.AreEqual("Container", e.Name);

                using (ZipFile nested = new ZipFile(zipFile.GetInputStream(0))) {
                    Assert.IsTrue(nested.TestArchive(true));
                    Assert.AreEqual(1, nested.Count);

                    Stream nestedStream = nested.GetInputStream(0);

                    StreamReader reader = new StreamReader(nestedStream);

                    string contents = reader.ReadToEnd();

                    Assert.AreEqual("Hello", contents);
                }
            }
        }
Example #20
0
        public void UnicodeNames()
        {
            MemoryStream memStream = new MemoryStream();
            using (ZipFile f = new ZipFile(memStream))
            {
                f.IsStreamOwner = false;

                f.BeginUpdate(new MemoryArchiveStorage());

                string[] names = new string[]
                {
                    "\u030A\u03B0",     // Greek
                    "\u0680\u0685",     // Arabic
                };

                foreach (string name in names)
                {
                    f.Add(new StringMemoryDataSource("Hello world"), name,
                          CompressionMethod.Deflated, true);
                }
                f.CommitUpdate();
                Assert.IsTrue(f.TestArchive(true));

                foreach (string name in names)
                {
                    int index = f.FindEntry(name, true);

                    Assert.IsTrue(index >= 0);
                    ZipEntry found = f[index];
                    Assert.AreEqual(name, found.Name);
                }
            }
        }
Example #21
0
        void TestEncryptedDirectoryEntry(MemoryStream s)
        {
            ZipOutputStream outStream = new ZipOutputStream(s);
            outStream.Password = "******";

            outStream.IsStreamOwner = false;
            outStream.PutNextEntry(new ZipEntry("YeUnreadableDirectory/"));
            outStream.Close();

            MemoryStream ms2 = new MemoryStream(s.ToArray());
            using (ZipFile zf = new ZipFile(ms2)) {
                Assert.IsTrue(zf.TestArchive(true));
            }
        }
Example #22
0
        public void UpdateCommentOnlyOnDisk()
        {
            string tempFile = GetTempFilePath();
            Assert.IsNotNull(tempFile, "No permission to execute this test?");

            tempFile = Path.Combine(tempFile, "SharpZipTest.Zip");
            if (File.Exists(tempFile))
            {
                File.Delete(tempFile);
            }

            using (ZipFile testFile = ZipFile.Create(tempFile))
            {
                testFile.BeginUpdate();
                testFile.Add(new StringMemoryDataSource("Aha"), "No1", CompressionMethod.Stored);
                testFile.Add(new StringMemoryDataSource("And so it goes"), "No2", CompressionMethod.Stored);
                testFile.Add(new StringMemoryDataSource("No3"), "No3", CompressionMethod.Stored);
                testFile.CommitUpdate();

                Assert.IsTrue(testFile.TestArchive(true));
            }

            using (ZipFile testFile = new ZipFile(tempFile))
            {
                Assert.IsTrue(testFile.TestArchive(true));
                Assert.AreEqual("", testFile.ZipFileComment);

                testFile.BeginUpdate(new DiskArchiveStorage(testFile, FileUpdateMode.Direct));
                testFile.SetComment("Here is my comment");
                testFile.CommitUpdate();

                Assert.IsTrue(testFile.TestArchive(true));
            }

            using (ZipFile testFile = new ZipFile(tempFile))
            {
                Assert.IsTrue(testFile.TestArchive(true));
                Assert.AreEqual("Here is my comment", testFile.ZipFileComment);
            }
            File.Delete(tempFile);

            // Variant using indirect updating.
            using (ZipFile testFile = ZipFile.Create(tempFile))
            {
                testFile.BeginUpdate();
                testFile.Add(new StringMemoryDataSource("Aha"), "No1", CompressionMethod.Stored);
                testFile.Add(new StringMemoryDataSource("And so it goes"), "No2", CompressionMethod.Stored);
                testFile.Add(new StringMemoryDataSource("No3"), "No3", CompressionMethod.Stored);
                testFile.CommitUpdate();

                Assert.IsTrue(testFile.TestArchive(true));
            }

            using (ZipFile testFile = new ZipFile(tempFile))
            {
                Assert.IsTrue(testFile.TestArchive(true));
                Assert.AreEqual("", testFile.ZipFileComment);

                testFile.BeginUpdate();
                testFile.SetComment("Here is my comment");
                testFile.CommitUpdate();

                Assert.IsTrue(testFile.TestArchive(true));
            }

            using (ZipFile testFile = new ZipFile(tempFile))
            {
                Assert.IsTrue(testFile.TestArchive(true));
                Assert.AreEqual("Here is my comment", testFile.ZipFileComment);
            }
            File.Delete(tempFile);
        }
Example #23
0
        public void ArchiveTesting()
        {
            byte[] originalData = null;
            byte[] compressedData = MakeInMemoryZip(ref originalData, CompressionMethod.Deflated,
                6, 1024, null, true);

            MemoryStream ms = new MemoryStream(compressedData);
            ms.Seek(0, SeekOrigin.Begin);

            using (ZipFile testFile = new ZipFile(ms))
            {

                Assert.IsTrue(testFile.TestArchive(true), "Unexpected error in archive detected");

                byte[] corrupted = new byte[compressedData.Length];
                Array.Copy(compressedData, corrupted, compressedData.Length);

                corrupted[123] = (byte)(~corrupted[123] & 0xff);
                ms = new MemoryStream(corrupted);
            }

            using (ZipFile testFile = new ZipFile(ms))
            {
                Assert.IsFalse(testFile.TestArchive(true), "Error in archive not detected");
            }
        }
Example #24
0
        void TestDirectoryEntry(MemoryStream s)
        {
            ZipOutputStream outStream = new ZipOutputStream(s);
            outStream.IsStreamOwner = false;
            outStream.PutNextEntry(new ZipEntry("YeOldeDirectory/"));
            outStream.Close();

            MemoryStream ms2 = new MemoryStream(s.ToArray());
            using (ZipFile zf = new ZipFile(ms2)) {
                Assert.IsTrue(zf.TestArchive(true));
            }
        }
Example #25
0
        public void BasicEncryption()
        {
            const string TestValue = "0001000";
            MemoryStream memStream = new MemoryStream();
            using (ZipFile f = new ZipFile(memStream)) {
                f.IsStreamOwner = false;
                f.Password = "******";

                StringMemoryDataSource m = new StringMemoryDataSource(TestValue);
                f.BeginUpdate(new MemoryArchiveStorage());
                f.Add(m, "a.dat");
                f.CommitUpdate();
                Assert.IsTrue(f.TestArchive(true), "Archive test should pass");
            }

            using (ZipFile g = new ZipFile(memStream)) {
                g.Password = "******";
                ZipEntry ze = g[0];

                Assert.IsTrue(ze.IsCrypted, "Entry should be encrypted");
                using (StreamReader r = new StreamReader(g.GetInputStream(0))) {
                    string data = r.ReadToEnd();
                    Assert.AreEqual(TestValue, data);
                }
            }
        }
Example #26
0
 private bool verifyDownload(string filepath)
 {
     try {
         using (ZipFile z = new ZipFile(filepath)) {
             return z.TestArchive(true);
         }
     }
     catch (Exception) {
         return false;
     }
 }
Example #27
0
        public void BasicEncryptionToDisk()
        {
            const string TestValue = "0001000";
            string tempFile = GetTempFilePath();
            Assert.IsNotNull(tempFile, "No permission to execute this test?");

            tempFile = Path.Combine(tempFile, "SharpZipTest.Zip");

            using (ZipFile f = ZipFile.Create(tempFile)) {
                f.Password = "******";

                StringMemoryDataSource m = new StringMemoryDataSource(TestValue);
                f.BeginUpdate();
                f.Add(m, "a.dat");
                f.CommitUpdate();
            }

            using (ZipFile f = new ZipFile(tempFile)) {
                f.Password = "******";
                Assert.IsTrue(f.TestArchive(true), "Archive test should pass");
            }

            using (ZipFile g = new ZipFile(tempFile)) {
                g.Password = "******";
                ZipEntry ze = g[0];

                Assert.IsTrue(ze.IsCrypted, "Entry should be encrypted");
                using (StreamReader r = new StreamReader(g.GetInputStream(0))) {
                    string data = r.ReadToEnd();
                    Assert.AreEqual(TestValue, data);
                }
            }

            File.Delete(tempFile);
        }
Example #28
0
        void Test(ArrayList fileSpecs)
        {
            var zipFileName = fileSpecs[0] as string;
            if (Path.GetExtension(zipFileName).Length == 0) {
                zipFileName = Path.ChangeExtension(zipFileName, ".zip");
            }

            using (ZipFile zipFile = new ZipFile(zipFileName)) {
                if ( zipFile.TestArchive(testData) ) {
                    Console.WriteLine("Archive test passed");
                } else {
                    Console.WriteLine("Archive test failure");
                }
            }
        }
Example #29
0
        internal static void manualInstallMod()
        {
            if (isInstalling)
            {
                notifier.Notify(NotificationType.Warning, "Already downloading a mod", "Please try again after a few seconds.");
                return;
            }
            isInstalling = true;

            using (var dlg = new OpenFileDialog()
            {
                CheckFileExists = true,
                CheckPathExists = true,
                DefaultExt = "zip",
                Filter = "Zip Files|*.zip",
                FilterIndex = 1,
                Multiselect = false,
                Title = "Choose the mod zip to install"
            })
            {
                //user pressed ok
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    //open the file in a stream
                    using (var fileStream = dlg.OpenFile())
                    {
                        ZipFile zip = new ZipFile(fileStream);

                        //check integrity
                        if (zip.TestArchive(true))
                        {
                            //look for the map file. It contains the mod name
                            ZipEntry map = zip.Cast<ZipEntry>().FirstOrDefault(a => a.Name.ToLower().EndsWith(".bsp"));

                            if (map != null)
                            {
                                //look for the version file
                                int entry = zip.FindEntry("addoninfo.txt", true);
                                if (entry >= 0)
                                {
                                    string allText = string.Empty;

                                    using (var infoStream = new StreamReader(zip.GetInputStream(entry)))
                                        allText = infoStream.ReadToEnd();

                                    string version = modController.ReadAddonVersion(allText);

                                    if (!string.IsNullOrEmpty(version))
                                    {
                                        Version v = new Version(version);
                                        string name = Path.GetFileNameWithoutExtension(map.Name).ToLower();

                                        //check if this same mod is already installed and if it needs an update
                                        if (modController.clientMods.Any(
                                            a => a.name.ToLower().Equals(name) && new Version(a.version) >= v))
                                        {
                                            MessageBox.Show("The mod you are trying to install is already installed or outdated.", "Mod Manual Install",
                                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                        }
                                        else
                                        {
                                            string targetDir = Path.Combine(d2mpDir, name);
                                            if (Directory.Exists(targetDir))
                                                Directory.Delete(targetDir, true);
                                            //Make the dir again
                                            Directory.CreateDirectory(targetDir);

                                            if (UnzipWithTemp(null, fileStream, targetDir))
                                            {
                                                refreshMods();
                                                log.Info("Mod manually installed!");
                                                notifier.Notify(NotificationType.Success, "Mod installed", "The following mod has been installed successfully: " + name);

                                                var mod = new ClientMod() {name = name, version = v.ToString()};
                                                var msg = new OnInstalledMod() {Mod = mod};

                                                Send(JObject.FromObject(msg).ToString(Formatting.None));

                                                var existing = modController.clientMods.FirstOrDefault(m => m.name == mod.name);
                                                if (existing != null) modController.clientMods.Remove(existing);
                                                
                                                modController.clientMods.Add(mod);
                                            }
                                            else
                                            {
                                                MessageBox.Show("The mod could not be installed. Read the log file for details.", "Mod Manual Install",
                                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        MessageBox.Show("Could not read the mod version from the zip file.", "Mod Manual Install",
                                            MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("No mod info was found in the zip file.", "Mod Manual Install",
                                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                }
                            }
                            else
                            {
                                MessageBox.Show("No mod map was found in the zip file.", "Mod Manual Install",
                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            }
                        }
                        else
                        {
                            MessageBox.Show("The zip file you selected seems to be invalid.", "Mod Manual Install",
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }
                    }
                }
            }

            isInstalling = false;
        }
Example #30
-4
        void TryDeleting(byte[] master, int totalEntries, int additions, params string[] toDelete)
        {
            MemoryStream ms = new MemoryStream();
            ms.Write(master, 0, master.Length);

            using (ZipFile f = new ZipFile(ms)) {
                f.IsStreamOwner = false;
                Assert.AreEqual(totalEntries, f.Count);
                Assert.IsTrue(f.TestArchive(true));
                f.BeginUpdate(new MemoryArchiveStorage());

                for (int i = 0; i < additions; ++i) {
                    f.Add(new StringMemoryDataSource("Another great file"),
                        string.Format("Add{0}.dat", i + 1));
                }

                foreach (string name in toDelete) {
                    f.Delete(name);
                }
                f.CommitUpdate();

                // write stream to file to assist debugging.
                // WriteToFile(@"c:\aha.zip", ms.ToArray());

                int newTotal = totalEntries + additions - toDelete.Length;
                Assert.AreEqual(newTotal, f.Count,
                    string.Format("Expected {0} entries after update found {1}", newTotal, f.Count));
                Assert.IsTrue(f.TestArchive(true), "Archive test should pass");
            }
        }
Example #31
-5
        public void AddToEmptyArchive()
        {
            string tempFile = GetTempFilePath();
            Assert.IsNotNull(tempFile, "No permission to execute this test?");

            string addFile = Path.Combine(tempFile, "a.dat");

            MakeTempFile(addFile, 1);

            try
            {
                tempFile = Path.Combine(tempFile, "SharpZipTest.Zip");

                using ( ZipFile f = ZipFile.Create(tempFile) )
                {
                    f.BeginUpdate();
                    f.Add(addFile);
                    f.CommitUpdate();
                    Assert.AreEqual(1, f.Count);
                    Assert.IsTrue(f.TestArchive(true));
                }

                using ( ZipFile f = new ZipFile(tempFile) )
                {
                    Assert.AreEqual(1, f.Count);
                    f.BeginUpdate();
                    f.Delete(f[0]);
                    f.CommitUpdate();
                    Assert.AreEqual(0, f.Count);
                    Assert.IsTrue(f.TestArchive(true));
                    f.Close();
                }

                File.Delete(tempFile);
            }
            finally
            {
                File.Delete(addFile);
            }
        }