Read() публичный Метод

Read a block of bytes from the stream.
Zero bytes read means end of stream.
public Read ( byte buffer, int offset, int count ) : int
buffer byte The destination for the bytes.
offset int The index to start storing data.
count int The number of bytes to attempt to read.
Результат int
Пример #1
0
		public static string ExtractArchive(string resourceFileName)
		{
			try
			{
				string extractDir = System.IO.Path.GetTempPath();
				extractDir = Path.Combine(extractDir, Guid.NewGuid().ToString());
				Directory.CreateDirectory(extractDir);

				string zipFilename = Path.Combine(extractDir, Guid.NewGuid().ToString());
				CreateFileFromResource(resourceFileName, zipFilename);

				ZipInputStream MyZipInputStream = null;
				FileStream MyFileStream = null;
				MyZipInputStream = new ZipInputStream(new FileStream(zipFilename, FileMode.Open, FileAccess.Read));
				ZipEntry MyZipEntry = MyZipInputStream.GetNextEntry();
				Directory.CreateDirectory(extractDir);
				while (MyZipEntry != null)
				{
					if (MyZipEntry.IsDirectory)
					{
						Directory.CreateDirectory(extractDir + @"\" + MyZipEntry.Name);
					}
					else
					{
						if (!Directory.Exists(extractDir + @"\" + Path.GetDirectoryName(MyZipEntry.Name)))
						{
							Directory.CreateDirectory(extractDir + @"\" + Path.GetDirectoryName(MyZipEntry.Name));
						}
						MyFileStream = new FileStream(extractDir + @"\" + MyZipEntry.Name, FileMode.OpenOrCreate, FileAccess.Write);
						int count;
						byte[] buffer = new byte[4096];
						count = MyZipInputStream.Read(buffer, 0, 4096);
						while (count > 0)
						{
							MyFileStream.Write(buffer, 0, count);
							count = MyZipInputStream.Read(buffer, 0, 4096);
						}
						MyFileStream.Close();
					}
					try
					{
						MyZipEntry = MyZipInputStream.GetNextEntry();
					}
					catch
					{
						MyZipEntry = null;
					}
				}

				if (MyZipInputStream != null)
					MyZipInputStream.Close();

				if (MyFileStream != null)
					MyFileStream.Close();

				return extractDir;
			}
			catch { throw; }

		}
Пример #2
0
	public static void Main(string[] args)
	{
		// Perform simple parameter checking.
		if ( args.Length < 1 ) {
			Console.WriteLine("Usage ViewZipFile NameOfFile");
			return;
		}
		
		if ( !File.Exists(args[0]) ) {
			Console.WriteLine("Cannot find file '{0}'", args[0]);
			return;
		}

		// For IO there should be exception handling but in this case its been ommitted
		
		byte[] data = new byte[4096];
		
		using (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);
				
				if ( theEntry.IsFile ) {
					
					// Assuming the contents are text may be ok depending on what you are doing
					// here its fine as its shows how data can be read from a Zip archive.
					Console.Write("Show entry text (y/n) ?");
					
					if (Console.ReadLine() == "y") {
						int size = s.Read(data, 0, data.Length);
						while (size > 0) {
							Console.Write(Encoding.ASCII.GetString(data, 0, size));
							size = s.Read(data, 0, data.Length);
						}
					}
					Console.WriteLine();
				}
			}
			
			// Close can be ommitted as the using statement will do it automatically
			// but leaving it here reminds you that is should be done.
			s.Close();
		}
	}
Пример #3
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);
    }
Пример #4
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);
    }
Пример #5
0
        public static string UnzipText(byte[] zippedText)
        {
            if (zippedText == null || zippedText.Length == 0) return "";

            StringBuilder sb = new StringBuilder();
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(zippedText))
            using (ZipInputStream s = new ZipInputStream(ms))
            {
                ZipEntry theEntry = s.GetNextEntry();
                byte[] data = new byte[1024];
                if (theEntry != null)
                {
                    while (true)
                    {
                        int size = s.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            sb.Append(System.Text.UTF8Encoding.UTF8.GetString(data, 0, size));
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
            return sb.ToString();
        }
Пример #6
0
 /// <summary>
 /// 解压缩文件
 /// </summary>
 /// <param name="输入压缩文件路径">要解压的压缩文件</param>
 /// <param name="解压缩目录">解压目标目录路径</param>
 public static void 解压缩(string 输入压缩文件路径, string 解压缩目录)
 {
     ZipInputStream inputStream = new ZipInputStream(File.OpenRead(输入压缩文件路径));
     ZipEntry theEntry;
     while ((theEntry = inputStream.GetNextEntry()) != null)
     {
         解压缩目录 += "/";
         string fileName = Path.GetFileName(theEntry.Name);
         string path = Path.GetDirectoryName(解压缩目录 + theEntry.Name) + "/";
         Directory.CreateDirectory(path);//生成解压目录
         if (fileName != String.Empty)
         {
             FileStream streamWriter = File.Create(path + fileName);//解压文件到指定的目录 
             int size = 2048;
             byte[] data = new byte[2048];
             while (true)
             {
                 size = inputStream.Read(data, 0, data.Length);
                 if (size > 0)
                 {
                     streamWriter.Write(data, 0, size);
                 }
                 else
                 {
                     break;
                 }
             }
             streamWriter.Close();
         }
     }
     inputStream.Close();
 }
Пример #7
0
 public void UnZipFile(string ZipedFile, string UnZipFile)
 {
     ZipInputStream zipInputStream = new ZipInputStream(File.OpenRead(ZipedFile));
     ZipEntry nextEntry;
     while ((nextEntry = zipInputStream.GetNextEntry()) != null)
     {
         string directoryName = Path.GetDirectoryName(UnZipFile);
         string fileName = Path.GetFileName(nextEntry.Name);
         Directory.CreateDirectory(directoryName);
         if (fileName != string.Empty)
         {
             FileStream fileStream = File.OpenWrite(UnZipFile);
             byte[] array = new byte[2048];
             while (true)
             {
                 int num = zipInputStream.Read(array, 0, array.Length);
                 if (num <= 0)
                 {
                     break;
                 }
                 fileStream.Write(array, 0, num);
             }
             fileStream.Close();
         }
     }
     zipInputStream.Close();
 }
Пример #8
0
        private static void DecompressAndWriteFile(string destination, ZipInputStream source)
        {
            FileStream wstream = null;

            try
            {
                // create a stream to write the file to
                wstream = File.Create(destination);

                const int block = 2048; // number of bytes to decompress for each read from the source

                var data = new byte[block]; // location to decompress the file to

                // now decompress and write each block of data for the zip file entry
                while (true)
                {
                    int size = source.Read(data, 0, data.Length);

                    if (size > 0)
                        wstream.Write(data, 0, size);
                    else
                        break; // no more data
                }
            }
            finally
            {
                if (wstream != null)
                    wstream.Close();
            }
        }
Пример #9
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Unzip a byte array and return unpacked data
		/// </summary>
		/// <param name="data">Byte array containing data to be unzipped</param>
		/// <returns>unpacked data</returns>
		/// ------------------------------------------------------------------------------------
		public static byte[] UnpackData(byte[] data)
		{
			if (data == null)
				return null;
			try
			{
				MemoryStream memStream = new MemoryStream(data);
				ZipInputStream zipStream = new ZipInputStream(memStream);
				zipStream.GetNextEntry();
				MemoryStream streamWriter = new MemoryStream();
				int size = 2048;
				byte[] dat = new byte[2048];
				while (true)
				{
					size = zipStream.Read(dat, 0, dat.Length);
					if (size > 0)
					{
						streamWriter.Write(dat, 0, size);
					}
					else
					{
						break;
					}
				}
				streamWriter.Close();
				zipStream.CloseEntry();
Пример #10
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();
        }
Пример #11
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);
 }
Пример #12
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;
                            }
                        }
                    }
                }
            }
            }
        }
Пример #13
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();
        }
Пример #14
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);
        }
Пример #15
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);
 }
Пример #16
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);
                     }
                 }
             }
         }
     }
 }
Пример #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();
 }
 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);
 }
Пример #19
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;
        }
Пример #20
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();
        }
Пример #21
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;
            }

        }
Пример #22
0
        private static void ExtractZipEntry(
            string destinationRootFolderPath,
            ZipInputStream zipStream,
            ZipEntry theEntry)
        {
            string fileName = Path.GetFileName(theEntry.Name);
            if (string.IsNullOrEmpty(fileName))
                return;

            string directoryName = Path.GetDirectoryName(theEntry.Name);
            if (string.IsNullOrEmpty(directoryName))
                return;

            // create directory
            string destinationFolderPath =
                Path.Combine(
                    destinationRootFolderPath,
                    directoryName);
            Directory.CreateDirectory(destinationFolderPath);

            string destinationFilePath = Path.Combine(destinationFolderPath, fileName);
            using (FileStream streamWriter = File.Create(destinationFilePath))
            {
                var data = new byte[2048];
                while (true)
                {
                    int size = zipStream.Read(data, 0, data.Length);
                    if (size > 0)
                        streamWriter.Write(data, 0, size);
                    else
                        break;
                }
            }
        }
Пример #23
0
        public string[] Estrai(string file)
        {
            string[] ret = null;
            int newsize = 0;

            if (!File.Exists(file))
            {
                Console.WriteLine("Cannot find file '{0}'", file);
                return null;
            }

            string directoryName = Path.GetDirectoryName(file);

            using (ZipInputStream s = new ZipInputStream(File.OpenRead(file)))
            {

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

                    newsize++;

                    Console.WriteLine(theEntry.Name);

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

                    if (fileName != String.Empty)
                    {
                        using (FileStream streamWriter = File.Create(System.IO.Path.Combine(directoryName, 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;
                                }
                            }
                        }
                    }

                    string[] tmp = new string[newsize];
                    tmp[newsize - 1] = System.IO.Path.Combine(directoryName, fileName);
                    if (ret != null)
                        System.Array.Copy(ret, tmp,
                        System.Math.Min(ret.Length, tmp.Length));
                    ret = tmp;

                }
            }

            return ret;
        }
Пример #24
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);
            });
        });
    }
Пример #25
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) {
                            
                        }
                    }
                }                
            }
        }
Пример #26
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");
        }
Пример #27
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();
	}
Пример #28
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);
                }
            }
        }
Пример #29
0
        public static string Unzip(string fileNameZip)
        {
            string path = Path.GetDirectoryName(fileNameZip);
            string folderName = Path.Combine(path, Path.GetFileNameWithoutExtension(fileNameZip));
            CreateDirectory(folderName);

            ZipInputStream strmZipInputStream = new ZipInputStream(File.OpenRead(fileNameZip));
            ZipEntry entry;
            while ((entry = strmZipInputStream.GetNextEntry()) != null)
            {
                FileStream fs = File.Create(Path.Combine(folderName, entry.Name));
                int size = 2048;
                byte[] data = new byte[2048];

                while (true)
                {
                    size = strmZipInputStream.Read(data, 0, data.Length);
                    if (size > 0)
                        fs.Write(data, 0, size);
                    else
                        break;
                }
                fs.Close();
            }
            strmZipInputStream.Close();
            return folderName;
        }
Пример #30
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();
                    }
                }
            }
        }
Пример #31
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;
 }
Пример #32
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;
    }
Пример #33
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);
                 }
             }
         }
     }
 }
Пример #34
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();
	}
        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();
            }
        }
Пример #36
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);
                                    }
                                }
                            }
                        }
                    }

                }
            }
        }
        /// <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);
        }
Пример #38
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;
        }
    }
Пример #39
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();
    }
Пример #40
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);
            }
        }
Пример #41
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);
    }