This is an InflaterInputStream that reads the files baseInputStream an zip archive one after another. It has a special method to get the zip entry of the next file. The zip entry contains information about the file name size, compressed size, Crc, etc. It includes support for Stored and Deflated entries.

Author of the original java version : Jochen Hoenicke
Inheritance: ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream
Esempio n. 1
0
 public static bool UnZipFile(string InputPathOfZipFile, string NewName)
 {
     bool ret = true;
     try
     {
         if (File.Exists(InputPathOfZipFile))
         {
             string baseDirectory = Path.GetDirectoryName(InputPathOfZipFile);
             using (ZipInputStream ZipStream = new
             ZipInputStream(File.OpenRead(InputPathOfZipFile)))
             {
                 ZipEntry theEntry;
                 while ((theEntry = ZipStream.GetNextEntry()) != null)
                 {
                     if (theEntry.IsFile)
                     {
                         if (theEntry.Name != "")
                         {
                             string strNewFile = @"" + baseDirectory + @"\" +
                                                 NewName;
                             if (File.Exists(strNewFile))
                             {
                                 //continue;
                             }
                             using (FileStream streamWriter = File.Create(strNewFile))
                             {
                                 int size = 2048;
                                 byte[] data = new byte[2048];
                                 while (true)
                                 {
                                     size = ZipStream.Read(data, 0, data.Length);
                                     if (size > 0)
                                         streamWriter.Write(data, 0, size);
                                     else
                                         break;
                                 }
                                 streamWriter.Close();
                             }
                         }
                     }
                     else if (theEntry.IsDirectory)
                     {
                         string strNewDirectory = @"" + baseDirectory + @"\" +
                                                 theEntry.Name;
                         if (!Directory.Exists(strNewDirectory))
                         {
                             Directory.CreateDirectory(strNewDirectory);
                         }
                     }
                 }
                 ZipStream.Close();
             }
         }
     }
     catch (Exception ex)
     {
         ret = false;
     }
     return ret;
 }
Esempio n. 2
0
        internal static byte[] Uncompress(byte[] p)
        {
            MemoryStream output = new MemoryStream();
            MemoryStream ms = new MemoryStream(p);
            using (ZipInputStream zis = new ZipInputStream(ms))
            {
                int size = 2048;
                byte[] data = new byte[size];

                if (zis.GetNextEntry() != null)
                {
                    while (true)
                    {
                        size = zis.Read(data, 0, size);
                        if (size > 0)
                        {
                            output.Write(data, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }

            return output.ToArray();
        }
Esempio n. 3
0
 public static void ReadInMemory(FileInfo zipFileName, Predicate<ZipEntry> filter, Action<MemoryStream> action)
 {
     using (ZipInputStream inputStream = new ZipInputStream(zipFileName.OpenRead()))
     {
         ZipEntry entry;
         while ((entry = inputStream.GetNextEntry()) != null)
         {
             if (filter(entry))
             {
                 using (MemoryStream stream = new MemoryStream())
                 {
                     int count = 0x800;
                     byte[] buffer = new byte[0x800];
                     if (entry.Size <= 0L)
                     {
                         goto Label_0138;
                     }
                 Label_0116:
                     count = inputStream.Read(buffer, 0, buffer.Length);
                     if (count > 0)
                     {
                         stream.Write(buffer, 0, count);
                         goto Label_0116;
                     }
                 Label_0138:
                     stream.Position = 0;
                     action(stream);
                 }
             }
         }
     }
 }
Esempio n. 4
0
    public void Decompress(string OutputFileName, string ZlibFileName)
    {
        System.IO.FileStream raw = System.IO.File.OpenRead(ZlibFileName);
        ICSharpCode.SharpZipLib.Zip.ZipInputStream Decompressor = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(raw);
        Decompressor.GetNextEntry();

        System.IO.FileStream output = System.IO.File.Create(OutputFileName);

        byte[] buf = new byte[1024];
        int    n   = 0;

        while (true)
        {
            n = Decompressor.Read(buf, 0, buf.Length);

            if (n == 0)
            {
                break;
            }
            else
            {
                output.Write(buf, 0, n);
            }
        }

        output.Close();

        Decompressor.Close();
        raw.Close();
        //delete(Decompressor);
        //delete(buf);
    }
Esempio n. 5
0
        /*		/// <summary>
         * /// Упаковка папки
         * /// </summary>
         * /// <param name="SourceFolder">путь к исходной папке</param>
         * /// <param name="DestinationZipFile">путь к результирующему zip-архиву</param>
         * /// <param name="CompressLevel">0-9, 9 being the highest level of compression</param>
         * /// <param name="Password">пароль архива. Если его нет, то задаем null</param>
         * /// <param name="BufferSize">буфер, обычно 4096</param>
         */
//		public void ZipFolder(string SourceFolder, string DestinationZipFile, int CompressLevel, string Password, int BufferSize)
//		{
//			List<string> DirList = new List<string>();
//			DirsParser( SourceFolder, ref DirList, false );
//
//			FileStream outputFileStream = new FileStream(DestinationZipFile, FileMode.Create);
//			ZipOutputStream zipOutStream = new ZipOutputStream(outputFileStream);
//			zipOutStream.SetLevel(CompressLevel);
//
//			bool IsCrypted = false;
//			if (Password != null && Password.Length > 0) {
//				zipOutStream.Password = Password;
//				IsCrypted = true;
//			}
//
//			foreach( string dir in DirList ) {
//				string[] FilesForZipList = Directory.GetFiles( dir );
//				if (FilesForZipList.Length == 0) {
//					// файлов нет. Создаем папку dir
//
//				}
//
//				foreach (string file in FilesForZipList) {
//					Stream inputStream = new FileStream(file, FileMode.Open);
//					ZipEntry zipEntry = new ZipEntry(Path.GetFileName(file));
//
//					//zipEntry.IsVisible = IsVisible;
//					zipEntry.IsCrypted = IsCrypted;
//					zipEntry.CompressionMethod = ICSharpCode.SharpZipLib.Zip.CompressionMethod.Deflated;
//					zipOutStream.PutNextEntry(zipEntry);
//					CopyStream(inputStream, zipOutStream, BufferSize);
//					inputStream.Close();
//					zipOutStream.CloseEntry();
//				}
//				zipOutStream.Finish();
//				zipOutStream.Close();
//			}
//		}

        //        public void AddFilesToZip(ref List<string> FilesForZipList, string DestinationZipFile, string Password, bool IsVisible, int BufferSize)
//		{
//			if (FilesForZipList.Count > 0){
        //              FileStream outputFileStream = new FileStream(DestinationZipFile, FileMode.Create);
        //              ZipOutputStream zipOutStream = new ZipOutputStream(outputFileStream);
        //              ZipFile zipFile = null;
//				// there may be files to copy from annother archive
//				zipFile = new ZipFile(DestinationZipFile);
//
//				bool IsCrypted = false;
//				if (Password != null && Password.Length > 0) {
//					zipFile.Password = Password;
//					// encrypt the zip file, if Password != null
//					zipOutStream.Password = Password;
//					IsCrypted = true;
//				}
//
//				foreach (string file in FilesForZipList) {
//					ZipEntry zipEntry = viewItem.Tag as ZipEntry;
//					Stream inputStream;
//					if (zipEntry == null) {
//						inputStream = new FileStream(file, FileMode.Open);
//						zipEntry = new ZipEntry(Path.GetFileName(file));
//					} else {
//						inputStream = zipFile.GetInputStream(zipEntry);
//					}
//					zipEntry.IsVisible = IsVisible;
//					zipEntry.IsCrypted = IsCrypted;
//					zipEntry.CompressionMethod = ICSharpCode.SharpZipLib.Zip.CompressionMethod.Deflated;
//					zipOutStream.PutNextEntry(zipEntry);
//					CopyStream(inputStream, zipOutStream, BufferSize);
//					inputStream.Close();
//					zipOutStream.CloseEntry();
//				}
//
//				if (zipFile != null) {
//					zipFile.Close();
//				}
//
//				zipOutStream.Finish();
//				zipOutStream.Close();
//			}
//		}
        #endregion

        /* ======================================================================================== */
        /*                                  Распаковка файлов										*/
        /* ======================================================================================== */
        #region  аспаковка файлов

        /// <summary>
        /// Распаковка конкретного файла FileName из zip архива ZipPath
        /// Возвращает: Строку string с данными распакованного файла
        /// </summary>
        /// <param name="ZipPath">Путь к исходному zip-файлу</param>
        /// <param name="FileName">Имя файла, который нужно распаковать</param>
        public string UnZipFileToString(string ZipPath, string FileName)
        {
            MemoryStream ms = new MemoryStream();

            ICSharpCode.SharpZipLib.Zip.ZipInputStream zis = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(
                new FileStream(ZipPath, FileMode.Open)
                );
            ICSharpCode.SharpZipLib.Zip.ZipEntry entry = null;
            while ((entry = zis.GetNextEntry()) != null)
            {
                if (entry.Name.ToLower() == FileName)
                {
                    int    size = 2048;
                    byte[] data = new byte[2048];
                    while (true)
                    {
                        size = zis.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            ms.Write(data, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
            if (ms.Length > 0)
            {
                byte[] bdata = ms.ToArray();
                return(Encoding.GetEncoding(getEncoding(bdata)).GetString(bdata));
            }
            return(string.Empty);
        }
Esempio n. 6
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Import a file containing translations for one or more lists.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		public bool ImportTranslatedLists(string filename, FdoCache cache, IProgress progress)
		{
#if DEBUG
			DateTime dtBegin = DateTime.Now;
#endif
			using (var inputStream = FileUtils.OpenStreamForRead(filename))
			{
				var type = Path.GetExtension(filename).ToLowerInvariant();
				if (type == ".zip")
				{
					using (var zipStream = new ZipInputStream(inputStream))
					{
						var entry = zipStream.GetNextEntry(); // advances it to where we can read the one zipped file.
						using (var reader = new StreamReader(zipStream, Encoding.UTF8))
							ImportTranslatedLists(reader, cache, progress);
					}
				}
				else
				{
					using (var reader = new StreamReader(inputStream, Encoding.UTF8))
						ImportTranslatedLists(reader, cache, progress);
				}
			}
#if DEBUG
			DateTime dtEnd = DateTime.Now;
			TimeSpan span = new TimeSpan(dtEnd.Ticks - dtBegin.Ticks);
			Debug.WriteLine(String.Format("Elapsed time for loading translated list(s) from {0} = {1}",
				filename, span.ToString()));
#endif
			return true;
		}
Esempio n. 7
0
 /// <summary>
 /// Распаковка 1-го файла из zip архива ZipPath
 /// Возвращает: Строку string с данными распакованного файла, если была распаковка. Иначе - пустую строку
 /// </summary>
 /// <param name="ZipPath">Путь к исходному zip-файлу</param>
 public string UnZipFB2FileToString(string ZipPath)
 {
     if (FilesWorker.isFB2Archive(ZipPath))
     {
         MemoryStream ms = new MemoryStream();
         ICSharpCode.SharpZipLib.Zip.ZipInputStream zis = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(
             new FileStream(ZipPath, FileMode.Open)
             );
         if (zis.GetNextEntry() != null)
         {
             int    size = 2048;
             byte[] data = new byte[2048];
             while (true)
             {
                 size = zis.Read(data, 0, data.Length);
                 if (size > 0)
                 {
                     ms.Write(data, 0, size);
                 }
                 else
                 {
                     break;
                 }
             }
             byte[] bdata = ms.ToArray();
             return(Encoding.GetEncoding(getEncoding(bdata)).GetString(bdata));
         }
     }
     return(string.Empty);
 }
Esempio n. 8
0
 public static void ExtractZipFile(string zipFileName, string dirName)
 {
     var data = new byte[readBufferSize];
     using (var zipStream = new ZipInputStream(File.OpenRead(zipFileName)))
     {
         ZipEntry entry;
         while ((entry = zipStream.GetNextEntry()) != null)
         {
             var fullName = Path.Combine(dirName, entry.Name);
             if (entry.IsDirectory && !Directory.Exists(fullName))
             {
                 Directory.CreateDirectory(fullName);
             }
             else if (entry.IsFile)
             {
                 var dir = Path.GetDirectoryName(fullName);
                 if (!Directory.Exists(dir))
                 {
                     Directory.CreateDirectory(dir);
                 }
                 using (var fileStream = File.Create(fullName))
                 {
                     int readed;
                     while ((readed = zipStream.Read(data, 0, readBufferSize)) > 0)
                     {
                         fileStream.Write(data, 0, readed);
                     }
                 }
             }
         }
     }
 }
Esempio n. 9
0
	public static void Main(string[] args)
	{
		ZipInputStream s = new ZipInputStream(File.OpenRead(args[0]));
		
		ZipEntry theEntry;
		while ((theEntry = s.GetNextEntry()) != null) {
			Console.WriteLine("Name : {0}", theEntry.Name);
			Console.WriteLine("Date : {0}", theEntry.DateTime);
			Console.WriteLine("Size : (-1, if the size information is in the footer)");
			Console.WriteLine("      Uncompressed : {0}", theEntry.Size);
			Console.WriteLine("      Compressed   : {0}", theEntry.CompressedSize);
			int size = 2048;
			byte[] data = new byte[2048];
			
			Console.Write("Show Entry (y/n) ?");
			
			if (Console.ReadLine() == "y") {
//				System.IO.Stream st = File.Create("G:\\a.tst");
				while (true) {
					size = s.Read(data, 0, data.Length);
//					st.Write(data, 0, size);
					if (size > 0) {
							Console.Write(new ASCIIEncoding().GetString(data, 0, size));
					} else {
						break;
					}
				}
//				st.Close();
			}
			Console.WriteLine();
		}
		s.Close();
	}
Esempio n. 10
0
        public static void UnzipFile(string directory, string zipFile, int patchNum)
        {
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(directory + zipFile)))
            {
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    string directoryName = Path.GetDirectoryName(theEntry.Name);

                    // create directory
                    if (directoryName.Length > 0)
                    {
                        Directory.CreateDirectory(directory + directoryName);
                    }
                    string fileName = directory + "-" + patchNum + theEntry.Name;
                    if (fileName.Contains("patch" + patchNum + "info"))
                    {
                        fileName = directory + theEntry.Name;
                    }
                    Console.WriteLine("Unzipping file: {0}", fileName);
                    using (FileStream streamWriter = File.Create(fileName))
                    {
                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0) streamWriter.Write(data, 0, size);
                            else break;
                        }
                    }
                    Console.WriteLine("Unzipped: {0}", theEntry.Name);
                }
            }
        }
Esempio n. 11
0
        public static void UnZip(byte[] inputZipBinary, string destinationPath)
        {
            DirectoryInfo outDirInfo = new DirectoryInfo(destinationPath);
            if (!outDirInfo.Exists)
                outDirInfo.Create();

            using (MemoryStream msZipBinary = new MemoryStream(inputZipBinary))
            {
                using (ZipInputStream zipFile = new ZipInputStream(msZipBinary))
                {
                    ZipEntry zipEntry;
                    while ((zipEntry = zipFile.GetNextEntry()) != null)
                    {
                        FileStream fsOut = File.Create(outDirInfo.FullName + "\\" + zipEntry.Name);
                        byte[] buffer = new byte[4096]; int count = 0;

            #if DEBUG
                        Console.WriteLine("Descomprimiendo: " + zipEntry.Name +
                            " |Tamaño comprimido: " + zipEntry.CompressedSize +
                            " |Tamano descomprimido: " + zipEntry.Size +
                            " |CRC: " + zipEntry.Crc);
            #endif

                        while ((count = zipFile.Read(buffer, 0, buffer.Length)) > 0)
                            fsOut.Write(buffer, 0, count);
                        fsOut.Flush();
                        fsOut.Close();
                    }
                }
            }
        }
Esempio n. 12
0
    public void Decompress(System.IO.Stream OutputStream, System.IO.Stream InputStream)
    {
        ICSharpCode.SharpZipLib.Zip.ZipInputStream Decompressor = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(InputStream);
        Decompressor.GetNextEntry();

        byte[] buf = new byte[1024];
        int    n   = 0;

        while (true)
        {
            n = Decompressor.Read(buf, 0, buf.Length);

            if (n == 0)
            {
                break;
            }
            else
            {
                OutputStream.Write(buf, 0, n);
            }
        }

        OutputStream.Seek(0, System.IO.SeekOrigin.Begin);
        Decompressor.Close();
        //delete(Decompressor);
        //delete(buf);
    }
        public void TestCompressWithContentType()
        {
            var pipeline = PipelineFactory.CreateEmptySendPipeline();

            var component = new CompressMessage();
            var msgPart2 = MessageHelper.CreatePartFromString("<testmessage2></testmessage2>");
            var msgPart3 = MessageHelper.CreatePartFromString("<testmessage3></testmessage3>");
            msgPart2.ContentType = "application/xml";
            msgPart3.ContentType = "application/xml";
            var msg = MessageHelper.CreateFromString("<testmessage1></testmessage1>");
            msg.AddPart("invoice2", msgPart2, false);
            msg.AddPart("invoice3", msgPart3, false);
            msg.BodyPart.ContentType = "application/xml";
            pipeline.AddComponent(component, PipelineStage.Encode);

            var result = pipeline.Execute(msg);

            ZipInputStream zipInputStream = new ZipInputStream(result.BodyPart.GetOriginalDataStream());
            ZipEntry zipEntry = zipInputStream.GetNextEntry();
            while (zipEntry != null)
            {
                Guid g;
                Assert.IsTrue(Guid.TryParse(Path.GetFileNameWithoutExtension(zipEntry.Name), out g));
                Assert.AreEqual(".xml", Path.GetExtension(zipEntry.Name));
                zipEntry = zipInputStream.GetNextEntry();
            }
        }
Esempio n. 14
0
        private static Dictionary<string, object> GetIpaPList(string filePath)
        {
            var plist = new Dictionary<string, object>();
            var zip = new ZipInputStream(File.OpenRead(filePath));
            using (var filestream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                var zipfile = new ZipFile(filestream);
                ZipEntry item;

                while ((item = zip.GetNextEntry()) != null)
                {
                    Match match = Regex.Match(item.Name.ToLower(), @"Payload/([A-Za-z0-9\-. ]+)\/info.plist$",
                        RegexOptions.IgnoreCase);
                    if (match.Success)
                    {
                        var bytes = new byte[50*1024];

                        using (Stream strm = zipfile.GetInputStream(item))
                        {
                            int size = strm.Read(bytes, 0, bytes.Length);

                            using (var s = new BinaryReader(strm))
                            {
                                var bytes2 = new byte[size];
                                Array.Copy(bytes, bytes2, size);
                                plist = (Dictionary<string, object>) PlistCS.readPlist(bytes2);
                            }
                        }

                        break;
                    }
                }
            }
            return plist;
        }
Esempio n. 15
0
        /// <summary>
        /// Prepares to extract a ZIP archive contained in a stream.
        /// </summary>
        /// <param name="stream">The stream containing the archive data to be extracted. Will be disposed when the extractor is disposed.</param>
        /// <param name="target">The path to the directory to extract into.</param>
        /// <exception cref="IOException">The archive is damaged.</exception>
        internal ZipExtractor([NotNull] Stream stream, [NotNull] string target)
            : base(target)
        {
            #region Sanity checks
            if (stream == null) throw new ArgumentNullException("stream");
            #endregion

            UnitsTotal = stream.Length;

            try
            {
                // Read the central directory
                using (var zipFile = new ZipFile(stream) {IsStreamOwner = false})
                {
                    _centralDirectory = new ZipEntry[zipFile.Count];
                    for (int i = 0; i < _centralDirectory.Length; i++)
                        _centralDirectory[i] = zipFile[i];
                }
                stream.Seek(0, SeekOrigin.Begin);

                _zipStream = new ZipInputStream(stream);
            }
                #region Error handling
            catch (ZipException ex)
            {
                // Wrap exception since only certain exception types are allowed
                throw new IOException(Resources.ArchiveInvalid, ex);
            }
            #endregion
        }
Esempio n. 16
0
        public void Extract(string path, string dest_dir)
        {
            ZipInputStream zipstream = new ZipInputStream(new FileStream( path, FileMode.Open));

              ZipEntry theEntry;
              while ((theEntry = zipstream.GetNextEntry()) != null) {
            string directoryName = Path.GetDirectoryName(theEntry.Name);
            string fileName      = Path.GetFileName(theEntry.Name);

            // create directory
            if (directoryName != String.Empty)
                Directory.CreateDirectory(directoryName);

            if (fileName != String.Empty) {
                FileStream streamWriter = File.Create( Path.Combine( dest_dir, theEntry.Name) );

                int size = 0;
                byte[] buffer = new byte[2048];
                while ((size = zipstream.Read(buffer, 0, buffer.Length)) > 0) {
                    streamWriter.Write(buffer, 0, size);
                }
                streamWriter.Close();
            }
              }
              zipstream.Close();
        }
Esempio n. 17
0
 public static void UnZipFile(string[] args)
 {
     ZipInputStream zipInputStream = new ZipInputStream((Stream) File.OpenRead(args[0].Trim()));
       string directoryName = Path.GetDirectoryName(args[1].Trim());
       if (!Directory.Exists(args[1].Trim()))
     Directory.CreateDirectory(directoryName);
       ZipEntry nextEntry;
       while ((nextEntry = zipInputStream.GetNextEntry()) != null)
       {
     string fileName = Path.GetFileName(nextEntry.Name);
     if (fileName != string.Empty)
     {
       FileStream fileStream = File.Create(args[1].Trim() + fileName);
       byte[] buffer = new byte[2048];
       while (true)
       {
     int count = zipInputStream.Read(buffer, 0, buffer.Length);
     if (count > 0)
       fileStream.Write(buffer, 0, count);
     else
       break;
       }
       fileStream.Close();
     }
       }
       zipInputStream.Close();
 }
Esempio n. 18
0
        public bool Decompress()
        {
            Boolean gotIt = false;
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
            {
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    if (theEntry.IsFile && theEntry.Name == m_msi)
                    {
                        gotIt = true;
                        FileStream streamWriter = File.Create(msiFilePath);
                        long filesize = theEntry.Size;
                        byte[] data = new byte[filesize];
                        while (true)
                        {
                            filesize = s.Read(data, 0, data.Length);
                            if (filesize > 0)
                            {
                                streamWriter.Write(data, 0, (int)filesize);
                            }
                            else
                            {
                                break;
                            }
                        }
                        streamWriter.Close();
                    }
                }
            }

            return gotIt;
        }
Esempio n. 19
0
        public static string UncompressContent(byte[] zippedContent)
        {
            try
            {
                MemoryStream inp = new MemoryStream(zippedContent);
                ZipInputStream zipin = new ZipInputStream(inp);
                ZipEntry entryin = zipin.GetNextEntry();
                byte[] buffout = new byte[(int)zipin.Length];
                zipin.Read(buffout, 0, (int)zipin.Length);

                MemoryStream decompress = new MemoryStream(buffout);

                System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
                
                string result = enc.GetString(decompress.ToArray());
                decompress.Dispose();
                inp.Dispose();

                return result;
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                return null;
            }

        }
        public KarFile(string fileName, ReportProgressFunction ReportProgress)
        {
            _fileName = fileName;
            _directory = FileFunctions.CreateTempoaryDirectory();
            using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            using (ZipInputStream zip = new ZipInputStream(file))
            {
                while (true)
                {
                    ZipEntry item = zip.GetNextEntry();
                    if (item == null)
                    {
                        break;
                    }

                    string itemDirectory = Path.GetDirectoryName(item.Name);
                    string itemName = Path.GetFileName(item.Name);

                    string outputDirectory = Path.Combine(_directory, itemDirectory);
                    FileFunctions.CreateDirectory(outputDirectory, ReportProgress);

                    string outputName = Path.Combine(outputDirectory, itemName);
                    StreamFunctions.ExportUntilFail(outputName, zip, ReportProgress);
                }

                zip.Close();
            }
        }
Esempio n. 21
0
    private void ParseZipAsync(byte[] zipFileData, Action <byte[]> callback)
    {
        Loom.RunAsync(() =>
        {
            MemoryStream stream = new MemoryStream(zipFileData);
            stream.Seek(0, SeekOrigin.Begin);
            ICSharpCode.SharpZipLib.Zip.ZipInputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(stream);

            for (ICSharpCode.SharpZipLib.Zip.ZipEntry theEntry = zipStream.GetNextEntry(); theEntry != null; theEntry = zipStream.GetNextEntry())
            {
                if (theEntry.IsFile == false)
                {
                    continue;
                }

                if (theEntry.Name.EndsWith(".meta"))
                {
                    continue;
                }

                string fileName = Path.GetFileName(theEntry.Name);
                if (fileName != String.Empty)
                {
                    List <byte> result = new List <byte>();
                    byte[] data        = new byte[2048];
                    while (true)
                    {
                        int size = zipStream.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            var bytes = new Byte[size];
                            Array.Copy(data, bytes, size);
                            result.AddRange(bytes);
                        }
                        else
                        {
                            break;
                        }
                    }

                    //文件名都转为小写
                    if (m_DictLuaScriptData.ContainsKey(fileName.ToLower()))
                    {
                        string str = string.Format("ResourcesManager.InitZip:Zip中文件名{0}重复", fileName);
                        Debug.LogError(str);
                        continue;
                    }
                    m_DictLuaScriptData.Add(theEntry.Name.ToLower(), result.ToArray());
                }
            }

            zipStream.Close();
            stream.Close();

            Loom.QueueOnMainThread(() =>
            {
                callback(zipFileData);
            });
        });
    }
Esempio n. 22
0
        public override void Add (string path)
        {
            using (var file_stream = new FileStream (path, FileMode.Open, FileAccess.Read))
            using (var zip_stream = new ZipInputStream (file_stream)) {                
                ZipEntry entry;
                while ((entry = zip_stream.GetNextEntry ()) != null) {
                    if (!entry.IsFile) {
                        continue;
                    }
                    var extension = Path.GetExtension (entry.Name);
                    if (!parser_for_parts.SupportedFileExtensions.Contains (extension)) {
                        continue;
                    }

                    using (var out_stream = new MemoryStream ()) {
                        int size;
                        var buffer = new byte[2048];
                        do {
                            size = zip_stream.Read (buffer, 0, buffer.Length);
                            out_stream.Write (buffer, 0, size);
                        } while (size > 0);

                        out_stream.Seek (0, SeekOrigin.Begin);
                        try {
                            parser_for_parts.Add (out_stream, entry.Name);
                        } catch (NotSupportedException) {
                            
                        }
                    }
                }                
            }
        }
Esempio n. 23
0
        public static void GetDefinitionStreamsFromBundle(string bundlePath, out Stream monoTodoDefinitions, out Stream notImplementedDefinitions, out Stream missingDefinitions)
        {
            ZipInputStream zs = new ZipInputStream (File.OpenRead (bundlePath));
            ZipEntry ze;

            monoTodoDefinitions = null;
            notImplementedDefinitions = null;
            missingDefinitions = null;

            while ((ze = zs.GetNextEntry ()) != null) {
                switch (ze.Name) {
                    case "monotodo.txt":
                        StreamReader sr = new StreamReader (zs);
                        string s = sr.ReadToEnd ();
                        monoTodoDefinitions = new MemoryStream (ASCIIEncoding.ASCII.GetBytes (s));
                        break;
                    case "exception.txt":
                        StreamReader sr2 = new StreamReader (zs);
                        string s2 = sr2.ReadToEnd ();
                        notImplementedDefinitions = new MemoryStream (ASCIIEncoding.ASCII.GetBytes (s2));
                        break;
                    case "missing.txt":
                        StreamReader sr3 = new StreamReader (zs);
                        string s3 = sr3.ReadToEnd ();
                        missingDefinitions = new MemoryStream (ASCIIEncoding.ASCII.GetBytes (s3));
                        break;
                    default:
                        break;
                }
            }
        }
Esempio n. 24
0
	public static void Main(string[] args)
	{
		ZipInputStream s = new ZipInputStream(File.OpenRead(args[0]));
		
		ZipEntry theEntry;
		while ((theEntry = s.GetNextEntry()) != null) {
			
			Console.WriteLine(theEntry.Name);
			
			string directoryName = Path.GetDirectoryName(theEntry.Name);
			string fileName      = Path.GetFileName(theEntry.Name);
			
			// create directory
			Directory.CreateDirectory(directoryName);
			
			if (fileName != String.Empty) {
				FileStream streamWriter = File.Create(theEntry.Name);
				
				int size = 2048;
				byte[] data = new byte[2048];
				while (true) {
					size = s.Read(data, 0, data.Length);
					if (size > 0) {
						streamWriter.Write(data, 0, size);
					} else {
						break;
					}
				}
				
				streamWriter.Close();
			}
		}
		s.Close();
	}
        public void TestCompressSingleMessagePart()
        {
            var pipeline = PipelineFactory.CreateEmptySendPipeline();

            var component = new CompressMessage {DefaultZipEntryFileExtension = "xml"};

            var msg = MessageHelper.CreateFromString("<testmessage1></testmessage1>");

            pipeline.AddComponent(component, PipelineStage.Encode);

            var result = pipeline.Execute(msg);

            ZipInputStream zipInputStream = new ZipInputStream(result.BodyPart.GetOriginalDataStream());
            ZipEntry zipEntry = zipInputStream.GetNextEntry();
            int i = 0;
            while (zipEntry != null)
            {
                Guid g;
                Assert.IsTrue(Guid.TryParse(Path.GetFileNameWithoutExtension(zipEntry.Name), out g));
                Assert.AreEqual(".xml", Path.GetExtension(zipEntry.Name));
                zipEntry = zipInputStream.GetNextEntry();
                i++;
            }

            Assert.AreEqual(1,i);
        }
Esempio n. 26
0
        // 압축을 해제한다.
        private void Unzip(string zipfile)
        {
            // 풀고자 하는 압축 파일 이름
            ZipInputStream s = new ZipInputStream(File.OpenRead(zipfile));

            ZipEntry theEntry;
            while ((theEntry = s.GetNextEntry()) != null)
            {
                // 압축을 풀고자 하는 대상 폴더 이름이 "C:\test" 인 경우
                string fullname = @"C:\zipTest" + theEntry.Name;

                string directoryName = Path.GetDirectoryName(fullname);
                string fileName = Path.GetFileName(fullname);

                if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName);

                if (fileName != String.Empty)
                {
                    FileStream streamWriter = File.Create(fullname);
                    int size = 2048;
                    byte[] data = new byte[2048];
                    while (true)
                    {
                        size = s.Read(data, 0, data.Length);
                        if (size > 0) streamWriter.Write(data, 0, size);
                        else break;
                    }
                    streamWriter.Close();
                }
            }
            s.Close();
        }
 private void RestoreFromFile(Stream file)
 {
         //
         //
         using (var store = IsolatedStorageFile.GetUserStoreForApplication()) {
                 using (var zip = new ZipInputStream(file)) {
                         try {
                                 while (true) {
                                         var ze = zip.GetNextEntry();
                                         if (ze == null) break;
                                         using (var f = new IsolatedStorageFileStream(ze.Name, FileMode.Create, store)) {
                                                 var fs = new byte[ze.Size];
                                                 zip.Read(fs, 0, fs.Length);
                                                 f.Write(fs, 0, fs.Length);
                                         }
                                 }
                         } catch {
                                 lblLastBackup.Text = StringResources.BackupAndRestorePage_Messages_RestoreFailed;
                                 App.ToastMe(StringResources.BackupAndRestorePage_Messages_RestoreFailed);
                                 return;
                         } finally {
                                 file.Close();
                                 ClearOldBackupFiles();
                                 App.ViewModel.IsRvDataChanged = true;
                         }
                 }
         }
         lblLastBackup.Text = StringResources.BackupAndRestorePage_Messages_RestoreSuccess;
         App.ToastMe(StringResources.BackupAndRestorePage_Messages_RestoreSuccess);
 }
Esempio n. 28
0
    /// <summary>
    /// 解压缩文件(压缩文件中含有子目录)
    /// </summary>
    /// <param name="zipfilepath">待解压缩的文件路径</param>
    /// <param name="unzippath">解压缩到指定目录</param>
    /// <returns>解压后的文件列表</returns>
    public List<string> UnZip(string zipfilepath, string unzippath)
    {
        //解压出来的文件列表
        List<string> unzipFiles = new List<string>();

        //检查输出目录是否以“\\”结尾
        if (unzippath.EndsWith("\\") == false || unzippath.EndsWith(":\\") == false)
        {
            unzippath += "\\";
        }

        ZipInputStream s = new ZipInputStream(File.OpenRead(zipfilepath));
        ZipEntry theEntry;
        while ((theEntry = s.GetNextEntry()) != null)
        {
            string directoryName = Path.GetDirectoryName(unzippath);
            string fileName = Path.GetFileName(theEntry.Name);

            //生成解压目录【用户解压到硬盘根目录时,不需要创建】
            if (!string.IsNullOrEmpty(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }

            if (fileName != String.Empty)
            {
                //如果文件的压缩后大小为0那么说明这个文件是空的,因此不需要进行读出写入
                if (theEntry.CompressedSize == 0)
                    break;
                //解压文件到指定的目录
                directoryName = Path.GetDirectoryName(unzippath + theEntry.Name);
                //建立下面的目录和子目录
                Directory.CreateDirectory(directoryName);

                //记录导出的文件
                unzipFiles.Add(unzippath + theEntry.Name);

                FileStream streamWriter = File.Create(unzippath + theEntry.Name);

                int size = 2048;
                byte[] data = new byte[2048];
                while (true)
                {
                    size = s.Read(data, 0, data.Length);
                    if (size > 0)
                    {
                        streamWriter.Write(data, 0, size);
                    }
                    else
                    {
                        break;
                    }
                }
                streamWriter.Close();
            }
        }
        s.Close();
        GC.Collect();
        return unzipFiles;
    }
Esempio n. 29
0
 /// <summary>
 /// 解压缩
 /// </summary>
 /// <param name="zipBytes">待解压数据</param>
 /// <returns></returns>
 public static byte[] UnZip(byte[] zipBytes)
 {
     ICSharpCode.SharpZipLib.Zip.ZipInputStream zipStream = null;
     ICSharpCode.SharpZipLib.Zip.ZipEntry       ent       = null;
     byte[] reslutBytes = null;
     try
     {
         using (System.IO.MemoryStream inputZipStream = new System.IO.MemoryStream(zipBytes))
         {
             zipStream = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(inputZipStream);
             if ((ent = zipStream.GetNextEntry()) != null)
             {
                 reslutBytes = new byte[zipStream.Length];
                 zipStream.Read(reslutBytes, 0, reslutBytes.Length);
             }
         }
     }
     finally
     {
         if (zipStream != null)
         {
             zipStream.Close();
             zipStream.Dispose();
         }
         if (ent != null)
         {
             ent = null;
         }
         GC.Collect();
         GC.Collect(1);
     }
     return(reslutBytes);
 }
Esempio n. 30
0
        /// <summary>
        /// 解压缩文件
        /// </summary>
        /// <param name="zipPath">源文件</param>
        /// <param name="directory">目标文件</param>
        /// <param name="password">密码</param>
        public void File(string zipPath, string directory, string password = null) {
            FileInfo objFile = new FileInfo(zipPath);
            if (!objFile.Exists || !objFile.Extension.ToUpper().Equals(".ZIP")) return;
            FileDirectory.DirectoryCreate(directory);

            ZipInputStream objZIS = new ZipInputStream(System.IO.File.OpenRead(zipPath));
            if (!password.IsNullEmpty()) objZIS.Password = password;
            ZipEntry objEntry;
            while ((objEntry = objZIS.GetNextEntry()) != null) {
                string directoryName = Path.GetDirectoryName(objEntry.Name);
                string fileName = Path.GetFileName(objEntry.Name);
                if (directoryName != String.Empty) FileDirectory.DirectoryCreate(directory + directoryName);
                if (fileName != String.Empty) {
                    FileStream streamWriter = System.IO.File.Create(Path.Combine(directory, objEntry.Name));
                    int size = 2048;
                    byte[] data = new byte[2048];
                    while (true) {
                        size = objZIS.Read(data, 0, data.Length);
                        if (size > 0) {
                            streamWriter.Write(data, 0, size);
                        } else {
                            break;
                        }
                    }
                    streamWriter.Close();
                }
            }
            objZIS.Close();
        }
Esempio n. 31
0
 protected Stream UnZip(Stream input)
 {
     var zipInputStream = new ZipInputStream(input);
     if (zipInputStream.GetNextEntry() == null)
         throw new ZipException("Can't unzip archive.");
     return zipInputStream;
 }
Esempio n. 32
0
        public static void Unzip(string file)
        {
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(file))) {

            ZipEntry theEntry;
            while ((theEntry = s.GetNextEntry()) != null) {

                Console.WriteLine(theEntry.Name);

                string directoryName = Path.GetDirectoryName(theEntry.Name);
                string fileName      = Path.GetFileName(theEntry.Name);

                // create directory
                if ( directoryName.Length > 0 ) {
                    Directory.CreateDirectory(directoryName);
                }

                if (fileName != String.Empty) {
                    using (FileStream streamWriter = File.Create(theEntry.Name)) {

                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true) {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0) {
                                streamWriter.Write(data, 0, size);
                            } else {
                                break;
                            }
                        }
                    }
                }
            }
            }
        }
Esempio n. 33
0
        public static void InstallApplication(string zipFileName, byte[] zipFileContent)
        {
            string folderName = zipFileName.Replace(".zip", "").Replace(".ZIP", "");
            string binFolder = HttpContext.Current.Server.MapPath("~/bin");
            if (Directory.Exists(binFolder + "/" + folderName))
                Directory.SetCreationTime(binFolder + "/" + folderName, DateTime.Now);
            Directory.CreateDirectory(binFolder + "/" + folderName);
            using (MemoryStream memStream = new MemoryStream(zipFileContent))
            {
                memStream.Position = 0;
                using (ZipInputStream zipInput = new ZipInputStream(memStream))
                {
                    ZipEntry current = zipInput.GetNextEntry();
                    while (current != null)
                    {
                        using (FileStream output = new FileStream(
                            binFolder + "/" + folderName + "/" + current.Name,
                            FileMode.Create,
                            FileAccess.Write))
                        {
                            byte[] buffer = new byte[current.Size];
                            zipInput.Read(buffer, 0, buffer.Length);
                            output.Write(buffer, 0, buffer.Length);
                        }
                        current = zipInput.GetNextEntry();
                    }
                }
            }
            Language.Instance.SetDefaultValue("ApplicationWasInstalledRedirecting", @"
A new application was installed, and hence we had to refresh the browser 
and you might need to login again...");
            AjaxManager.Instance.Redirect("~/?message=ApplicationWasInstalledRedirecting");
        }
        public static void UnZip(this FileInfo fileInfo, string destiantionFolder)
        {
            using (var fileStreamIn = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read))
            {
                using (var zipInStream = new ZipInputStream(fileStreamIn))
                {
                    var entry = zipInStream.GetNextEntry();
                    FileStream fileStreamOut = null;
                    while (entry != null)
                    {
                        fileStreamOut = new FileStream(destiantionFolder + @"\" + entry.Name, FileMode.Create, FileAccess.Write);
                        int size;
                        byte[] buffer = new byte[4096];
                        do
                        {
                            size = zipInStream.Read(buffer, 0, buffer.Length);
                            fileStreamOut.Write(buffer, 0, size);
                        } while (size > 0);

                        fileStreamOut.Close();
                        entry = zipInStream.GetNextEntry();
                    }

                    if (fileStreamOut != null)
                        fileStreamOut.Close();
                    zipInStream.Close();
                }
                fileStreamIn.Close();
            }
        }
Esempio n. 35
0
        protected override void ImportMethod()
        {
            using (Utils.ProgressBlock progress = new Utils.ProgressBlock(this, STR_IMPORT, STR_DOWNLOAD, 1, 0))
            {
                using (System.IO.TemporaryFile tmp = new System.IO.TemporaryFile(true))
                using (System.Net.WebClient wc = new System.Net.WebClient())
                {
                    wc.DownloadFile("http://www.globalcaching.eu/service/cachedistance.aspx?country=Netherlands&prefix=GC", tmp.Path);

                    using (var fs = System.IO.File.OpenRead(tmp.Path))
                    using (ZipInputStream s = new ZipInputStream(fs))
                    {
                        ZipEntry theEntry = s.GetNextEntry();
                        byte[] data = new byte[1024];
                        if (theEntry != null)
                        {
                            StringBuilder sb = new StringBuilder();
                            while (true)
                            {
                                int size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    if (sb.Length == 0 && data[0] == 0xEF && size > 2)
                                    {
                                        sb.Append(System.Text.ASCIIEncoding.UTF8.GetString(data, 3, size - 3));
                                    }
                                    else
                                    {
                                        sb.Append(System.Text.ASCIIEncoding.UTF8.GetString(data, 0, size));
                                    }
                                }
                                else
                                {
                                    break;
                                }
                            }

                            XmlDocument doc = new XmlDocument();
                            doc.LoadXml(sb.ToString());
                            XmlElement root = doc.DocumentElement;
                            XmlNodeList nl = root.SelectNodes("wp");
                            if (nl != null)
                            {
                                Core.Geocaches.AddCustomAttribute(CUSTOM_ATTRIBUTE);
                                foreach (XmlNode n in nl)
                                {
                                    var gc = Utils.DataAccess.GetGeocache(Core.Geocaches, n.Attributes["code"].InnerText);
                                    if (gc != null)
                                    {
                                        string dist = Utils.Conversion.StringToDouble(n.Attributes["dist"].InnerText).ToString("000.0");
                                        gc.SetCustomAttribute(CUSTOM_ATTRIBUTE, dist);
                                    }
                                }
                            }
                        }
                    }

                }
            }
        }
Esempio n. 36
0
        // select the right decompression stream
        public override Stream GetResponseStream()
        {
            try
            {
                Stream responseStream = _response.GetResponseStream();
                Stream compressedStream = null;
                if (_response.ContentEncoding == "gzip")
                {
                    compressedStream = new
                      GZipInputStream(responseStream);
                }
                else if (_response.ContentEncoding == "deflate")
                {
                    compressedStream = new
                      ZipInputStream(responseStream);
                }

                if (compressedStream == null)
                    compressedStream = responseStream;

                if (compressedStream != null)
                {
                    // Decompress
                    MemoryStream decompressedStream = new MemoryStream();
                    int totalSize = 0;
                    int size = 2048;
                    byte[] writeData = new byte[2048];
                    while (true)
                    {
                        size = compressedStream.Read(writeData, 0, size);
                        totalSize += size;
                        if (size > 0)
                            decompressedStream.Write(writeData, 0, size);
                        else
                            break;
                    }

                    if (compressedStream != responseStream)
                        responseStream.Close();
                    compressedStream.Close();

                    decompressedStream.Seek(0, SeekOrigin.Begin);

                    using (MemoryStream logstream = new MemoryStream(decompressedStream.GetBuffer()))
                    using (StreamReader sr = new StreamReader(logstream))
                    {
                        DebugHelper.WriteLogEntry("ResponseStream: " + sr.ReadToEnd());
                    }

                    decompressedStream.Seek(0, SeekOrigin.Begin);
                    return decompressedStream;
                }
                return compressedStream;
            }
            catch (Exception ex)
            {
                DebugHelper.WriteLogEntry(ex, "GZIP error");
                return null;
            }
        }
Esempio n. 37
0
    static public long GetDeCompressFileSize(string zipPath)
    {
        long res = 0;

        System.IO.FileStream fs = new System.IO.FileStream(zipPath,
                                                           System.IO.FileMode.Open,
                                                           System.IO.FileAccess.Read, System.IO.FileShare.Read);

        ICSharpCode.SharpZipLib.Zip.ZipInputStream zis =
            new ICSharpCode.SharpZipLib.Zip.ZipInputStream(fs);

        try
        {
            ICSharpCode.SharpZipLib.Zip.ZipEntry ze;
            while ((ze = zis.GetNextEntry()) != null)
            {
                if (!ze.IsDirectory)
                {
                    res += ze.Size;
                }
            }
        }
        catch (Exception e)
        {
            Debug.Log(e);
            res = 0;
        }

        zis.Close();
        fs.Close();

        return(res);
    }
        /// <summary>
        /// zip解压文件
        /// </summary>
        /// <param name="strFilePath">压缩文件的名称,如:*.zip</param>
        /// <param name="dir">dir要解压的文件夹路径, 会自动带上文件名</param>
        /// <returns></returns>
        public bool UnzipZip(string strFilePath, string dir)
        {
            if (!File.Exists(strFilePath))
            {
                return(false);
            }

            dir = Path.Combine(dir, Path.GetFileNameWithoutExtension(strFilePath));

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            using FileStream fr = new FileStream(strFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            using ICSharpCode.SharpZipLib.Zip.ZipInputStream s = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(fr);
            ICSharpCode.SharpZipLib.Zip.ZipEntry theEntry;
            while ((theEntry = s.GetNextEntry()) != null)
            {
                string directoryName = Path.GetDirectoryName(theEntry.Name);
                string fileName      = Path.GetFileName(theEntry.Name);

                if (directoryName != String.Empty)
                {
                    Directory.CreateDirectory(Path.Combine(dir, directoryName));
                }

                if (fileName != String.Empty)
                {
                    using FileStream streamWriter = File.Create(Path.Combine(dir, theEntry.Name));

                    int    size = 2048;
                    byte[] data = new byte[2048];
                    while (true)
                    {
                        size = s.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            streamWriter.Write(data, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }

            return(true);
        }
Esempio n. 39
0
    /// <summary>
    /// Unpack the file no progress.
    /// </summary>
    public void Unpack(string file, string dir)
    {
        try
        {
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            ICSharpCode.SharpZipLib.Zip.ZipInputStream s = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(file));
            ICSharpCode.SharpZipLib.Zip.ZipEntry       theEntry;

            byte[] data = new byte[2048];
            while ((theEntry = s.GetNextEntry()) != null)
            {
                string directoryName = Path.GetDirectoryName(theEntry.Name);
                string fileName      = Path.GetFileName(theEntry.Name);
                if (directoryName != String.Empty)
                {
                    Directory.CreateDirectory(dir + directoryName);
                }

                if (fileName != String.Empty)
                {
                    CurFileName = theEntry.Name;
                    FileStream streamWriter = File.Create(dir + theEntry.Name);
                    int        size         = 2048;
                    while (true)
                    {
                        size = s.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            streamWriter.Write(data, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }
                    streamWriter.Close();
                }
            }
            s.Close();
            GC.Collect();
        }catch (Exception)
        {
            throw;
        }
    }
Esempio n. 40
0
        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        static public string CompressStrZip(string param)
        {
            byte[] data = System.Text.Encoding.UTF8.GetBytes(param);
            //byte[] data = Convert.FromBase64String(param);
            MemoryStream ms     = new MemoryStream();
            Stream       stream = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(ms);

            try
            {
                stream.Write(data, 0, data.Length);
            }
            finally
            {
                stream.Close();
                ms.Close();
            }
            return(Convert.ToBase64String(ms.ToArray()));
        }
Esempio n. 41
0
        private void ExtractFfmpeg()
        {
            Stream zipStream;

            zipStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("RESTCam.ffmpeg_x64.zip");
            var ziStream = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(zipStream);

            byte[]   buffer    = new byte[4096];
            ZipEntry nextEntry = ziStream.GetNextEntry();

            while (nextEntry != null)
            {
                string extractPath = Path.Combine(FfmpegBinFolder.FullName, nextEntry.Name);
                using (FileStream streamWriter = File.Create(extractPath))
                {
                    StreamUtils.Copy(ziStream, streamWriter, buffer);
                }
                nextEntry = ziStream.GetNextEntry();
            }
        }
Esempio n. 42
0
        public static ApkInfo ReadApkFromPath(string path)
        {
            NativeMethods.Log("ReadApkFromPath: " + path);
            byte[] manifestData  = null;
            byte[] resourcesData = null;
            using (ICSharpCode.SharpZipLib.Zip.ZipInputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(path)))
            {
                using (var filestream = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    ICSharpCode.SharpZipLib.Zip.ZipFile  zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(filestream);
                    ICSharpCode.SharpZipLib.Zip.ZipEntry item;
                    while ((item = zip.GetNextEntry()) != null)
                    {
                        if (item.Name.ToLower() == "androidmanifest.xml")
                        {
                            manifestData = new byte[50 * 1024];
                            using (Stream strm = zipfile.GetInputStream(item))
                            {
                                strm.Read(manifestData, 0, manifestData.Length);
                            }
                        }
                        if (item.Name.ToLower() == "resources.arsc")
                        {
                            using (Stream strm = zipfile.GetInputStream(item))
                            {
                                using (BinaryReader s = new BinaryReader(strm))
                                {
                                    resourcesData = s.ReadBytes((int)s.BaseStream.Length);
                                }
                            }
                        }
                    }
                }
            }

            ApkReader apkReader = new ApkReader();
            ApkInfo   info      = apkReader.extractInfo(manifestData, resourcesData);

            return(info);
        }
Esempio n. 43
0
        /// <summary>
        /// 解压
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        static public string DecompressStrZip(string param)
        {
            string commonString = "";

            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(param);
            //byte[] buffer=Convert.FromBase64String(param);
            MemoryStream ms = new MemoryStream(buffer);
            Stream       sm = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(ms);
            //这里要指明要读入的格式,要不就有乱码
            StreamReader reader = new StreamReader(sm, System.Text.Encoding.UTF8);

            try
            {
                commonString = reader.ReadToEnd();
            }
            finally
            {
                sm.Close();
                ms.Close();
            }
            return(commonString);
        }
Esempio n. 44
0
    IEnumerator UnpackAsync(string file, string dir, int count)
    {
        int index = 0;

        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }
        ICSharpCode.SharpZipLib.Zip.ZipInputStream s = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(file));
        ICSharpCode.SharpZipLib.Zip.ZipEntry       theEntry;


        byte[] data = new byte[1024];
        while ((theEntry = s.GetNextEntry()) != null)
        {
            index++;
            if (index % (count / 50) == 0)
            {
                yield return(0);
            }
            Progress = (float)index / (float)count;
            string directoryName = Path.GetDirectoryName(theEntry.Name);
            string fileName      = Path.GetFileName(theEntry.Name);
            if (directoryName != String.Empty)
            {
                Directory.CreateDirectory(dir + directoryName);
            }

            if (fileName != String.Empty)
            {
//		        FileStream streamWriter = File.Create(dir + theEntry.Name);
//				int size = 2048;
//		        while (true)
//		        {
//					size = s.Read(data, 0, data.Length);
//					if (size > 0)
//					{
//						streamWriter.Write(data, 0, size);
//					}
//					else
//					{
//						break;
//					}
//		        }
//	            streamWriter.Close();
                CurFileName = theEntry.Name;
                using (FileStream streamWriter = File.Create(dir + theEntry.Name))
                {
                    int size = s.Read(data, 0, data.Length);
                    while (size > 0)
                    {
                        streamWriter.Write(data, 0, size);
                        size = s.Read(data, 0, data.Length);
                    }
                    streamWriter.Close();
                }
            }
        }
        Progress = 1;
        s.Close();
        GC.Collect();
    }
Esempio n. 45
0
    // 해제
    static public bool DeCompression(string zipPath, string dest, ref string Exception)
    {
        string extractDir = dest;

        System.IO.FileStream fs = new System.IO.FileStream(zipPath,
                                                           System.IO.FileMode.Open,
                                                           System.IO.FileAccess.Read, System.IO.FileShare.Read);

        ICSharpCode.SharpZipLib.Zip.ZipInputStream zis =
            new ICSharpCode.SharpZipLib.Zip.ZipInputStream(fs);

        bool bRes = true;

        try
        {
            long t_size = 0;

            ICSharpCode.SharpZipLib.Zip.ZipEntry ze;

            while ((ze = zis.GetNextEntry()) != null)
            {
                if (!ze.IsDirectory)
                {
                    string fileName = System.IO.Path.GetFileName(ze.Name);
                    string destDir  = System.IO.Path.Combine(extractDir,
                                                             System.IO.Path.GetDirectoryName(ze.Name));

                    if (false == Directory.Exists(destDir))
                    {
                        System.IO.Directory.CreateDirectory(destDir);
                    }

                    string destPath = System.IO.Path.Combine(destDir, fileName);

                    System.IO.FileStream writer = new System.IO.FileStream(
                        destPath, System.IO.FileMode.Create,
                        System.IO.FileAccess.Write,
                        System.IO.FileShare.Write);

                    byte[] buffer = new byte[2048];
                    int    len;
                    while ((len = zis.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        writer.Write(buffer, 0, len);
                    }

                    writer.Close();

                    if (m_CB_DeCompress != null)
                    {
                        t_size += ze.Size;
                        m_CB_DeCompress(t_size);
                    }
                }
            }
        }
        catch (Exception e)
        {
            bRes      = false;
            Exception = e.Message;
        }

        zis.Close();
        fs.Close();

        return(bRes);
    }
Esempio n. 46
0
        /// <summary>
        /// 解压功能(解压压缩文件到指定目录)
        /// </summary>
        /// <param name="FileToUpZip">待解压的文件</param>
        /// <param name="ZipedFolder">指定解压目标目录</param>
        public static void UnZip(string FileToUpZip, string ZipedFolder)
        {
            if (!File.Exists(FileToUpZip))
            {
                return;
            }

            if (!Directory.Exists(ZipedFolder))
            {
                Directory.CreateDirectory(ZipedFolder);
            }

            ICSharpCode.SharpZipLib.Zip.ZipInputStream s        = null;
            ICSharpCode.SharpZipLib.Zip.ZipEntry       theEntry = null;

            string     fileName;
            FileStream streamWriter = null;

            try
            {
                s = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(FileToUpZip));
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    if (theEntry.Name != String.Empty)
                    {
                        fileName = Path.Combine(ZipedFolder, theEntry.Name);
                        ///判断文件路径是否是文件夹

                        if (fileName.EndsWith("/") || fileName.EndsWith("\\"))
                        {
                            Directory.CreateDirectory(fileName);
                            continue;
                        }

                        streamWriter = File.Create(fileName);
                        int    size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
            finally
            {
                if (streamWriter != null)
                {
                    streamWriter.Close();
                    streamWriter = null;
                }
                if (theEntry != null)
                {
                    theEntry = null;
                }
                if (s != null)
                {
                    s.Close();
                    s = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
        }