• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# ZipEntry类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中ZipEntry的典型用法代码示例。如果您正苦于以下问题:C# ZipEntry类的具体用法?C# ZipEntry怎么用?C# ZipEntry使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



ZipEntry类属于命名空间,在下文中一共展示了ZipEntry类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: zip

    private void zip(string strFile, ZipOutputStream s, string staticFile)
    {
        if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar) strFile += Path.DirectorySeparatorChar;
        Crc32 crc = new Crc32();
        string[] filenames = Directory.GetFileSystemEntries(strFile);
        foreach (string file in filenames)
        {

            if (Directory.Exists(file))
            {
                zip(file, s, staticFile);
            }

            else // 否则直接压缩文件
            {
                //打开压缩文件
                FileStream fs = File.OpenRead(file);

                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                string tempfile = file.Substring(staticFile.LastIndexOf("\\") + 1);
                ZipEntry entry = new ZipEntry(tempfile);

                entry.DateTime = DateTime.Now;
                entry.Size = fs.Length;
                fs.Close();
                crc.Reset();
                crc.Update(buffer);
                entry.Crc = crc.Value;
                s.PutNextEntry(entry);

                s.Write(buffer, 0, buffer.Length);
            }
        }
    }
开发者ID:QingWei-Li,项目名称:AutoBackupFolder,代码行数:35,代码来源:ZipFloClass.cs


示例2: Compress

    public static void Compress(string path, ZipOutputStream output, string relativePath)
    {
        if (!string.IsNullOrEmpty(relativePath) && !relativePath.EndsWith("\\"))
        {
            relativePath += "\\";
        }

        if (Directory.Exists(path))
        {
            FileSystemInfo[] fsis = new DirectoryInfo(path).GetFileSystemInfos();
            ZipEntry entry = new ZipEntry(relativePath + Path.GetFileName(path) + "/");
            entry.DateTime = DateTime.Now;
            output.PutNextEntry(entry);
            foreach (FileSystemInfo fsi in fsis)
            {
                Compress(path + "\\" + fsi.Name, output, relativePath + Path.GetFileName(path));
            }
        }
        else
        {
            Crc32 crc = new Crc32();
            //打开压缩文件
            Stream fs = File.Open(path, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[fs.Length];
            fs.Read(buffer, 0, buffer.Length);
            ZipEntry entry = new ZipEntry(relativePath + Path.GetFileName(path));
            entry.DateTime = DateTime.Now;
            fs.Close();
            crc.Reset();
            crc.Update(buffer);
            entry.Crc = crc.Value;
            output.PutNextEntry(entry);
            output.Write(buffer, 0, buffer.Length);
        }
    }
开发者ID:cyyt,项目名称:Lesktop,代码行数:35,代码来源:install.aspx.cs


示例3: ZipFiles

    public static void ZipFiles(string inputFolderPath, string outPath, string password)
    {
        ArrayList ar = GenerateFileList(inputFolderPath); // generate file list
        int TrimLength = (Directory.GetParent(inputFolderPath)).ToString().Length;
        // find number of chars to remove     // from orginal file path
        TrimLength += 1; //remove '\'
        FileStream ostream;
        byte[] obuffer;
        ZipOutputStream oZipStream = new ZipOutputStream(File.Create(outPath)); // create zip stream
        if (password != null && password != String.Empty)
            oZipStream.Password = password;
        oZipStream.SetLevel(9); // maximum compression
        ZipEntry oZipEntry;
        foreach (string Fil in ar) // for each file, generate a zipentry
        {
            oZipEntry = new ZipEntry(Fil.Remove(0, TrimLength));
            oZipStream.PutNextEntry(oZipEntry);

            if (!Fil.EndsWith(@"/")) // if a file ends with '/' its a directory
            {
                ostream = File.OpenRead(Fil);
                obuffer = new byte[ostream.Length];
                ostream.Read(obuffer, 0, obuffer.Length);
                oZipStream.Write(obuffer, 0, obuffer.Length);
                ostream.Close();
            }
        }
        oZipStream.Finish();
        oZipStream.Close();
    }
开发者ID:chutinhha,项目名称:web-quan-ly-kho,代码行数:30,代码来源:clsZip.cs


示例4: ZipFile

 /// <summary>
 /// 压缩单个文件
 /// </summary>
 /// <param name="fileToZip">要进行压缩的文件名</param>
 /// <param name="zipedFile">压缩后生成的压缩文件名</param>
 /// <param name="level">压缩等级</param>
 /// <param name="password">密码</param>
 /// <param name="onFinished">压缩完成后的代理</param>
 public static void ZipFile(string fileToZip, string zipedFile, string password = "", int level = 5, OnFinished onFinished = null)
 {
     //如果文件没有找到,则报错
     if (!File.Exists(fileToZip))
         throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!");
     using (FileStream fs = File.OpenRead(fileToZip))
     {
         byte[] buffer = new byte[fs.Length];
         fs.Read(buffer, 0, buffer.Length);
         fs.Close();
         using (FileStream ZipFile = File.Create(zipedFile))
         {
             using (ZipOutputStream ZipStream = new ZipOutputStream(ZipFile))
             {
                 string fileName = fileToZip.Substring(fileToZip.LastIndexOf("/") + 1);
                 ZipEntry ZipEntry = new ZipEntry(fileName);
                 ZipStream.PutNextEntry(ZipEntry);
                 ZipStream.SetLevel(level);
                 ZipStream.Password = password;
                 ZipStream.Write(buffer, 0, buffer.Length);
                 ZipStream.Finish();
                 ZipStream.Close();
                 if (null != onFinished) onFinished();
             }
         }
     }
 }
开发者ID:ZeroToken,项目名称:MyTools,代码行数:35,代码来源:ZipHelper.cs


示例5: Compression

 private static byte[] Compression(byte[] bytes)
 {
     MemoryStream ms = new MemoryStream();
     ZipOutputStream zos = new ZipOutputStream(ms);
     ZipEntry ze = new ZipEntry(ConfigConst.ZipEntryName);
     zos.PutNextEntry(ze);
     zos.SetLevel(9);
     zos.Write(bytes, 0, bytes.Length);//写入压缩文件
     zos.Close();
     return ms.ToArray();
 }
开发者ID:moto2002,项目名称:NewPhoenix,代码行数:11,代码来源:RefreshConfigEditor.cs


示例6: WriteZipFile

        public static void WriteZipFile(List<FileDetails> filesToZip, string path,string manifestPath,string manifest )
        {
            int compression = 9;
          
            FileDetails fd = new FileDetails(manifest, manifestPath,manifestPath);
            filesToZip.Insert(0,fd);

            foreach (FileDetails obj in filesToZip)
                if (!File.Exists(obj.FilePath))
                    throw new ArgumentException(string.Format("The File {0} does not exist!", obj.FileName));

            Object _locker=new Object();
            lock(_locker)
            {
                Crc32 crc32 = new Crc32();
                ZipOutputStream stream = new ZipOutputStream(File.Create(path));
                stream.SetLevel(compression);
                for (int i = 0; i < filesToZip.Count; i++)
                {
                    ZipEntry entry = new ZipEntry(filesToZip[i].FolderInfo + "/" + filesToZip[i].FileName);
                    entry.DateTime = DateTime.Now;
                    if (i == 0)
                    {
                        entry = new ZipEntry(manifest);
                    }

                    using (FileStream fs = File.OpenRead(filesToZip[i].FilePath))
                    {
                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        entry.Size = fs.Length;
                        fs.Close();
                        crc32.Reset();
                        crc32.Update(buffer);
                        entry.Crc = crc32.Value;
                        stream.PutNextEntry(entry);
                        stream.Write(buffer, 0, buffer.Length);
                    }
                }
                stream.Finish();
                stream.Close();
                DeleteManifest(manifestPath);
            }
            

          

           
        }
开发者ID:electrono,项目名称:veg-web,代码行数:49,代码来源:PackageWriterBase.cs


示例7: Evaluate

 internal override bool Evaluate(ZipEntry entry)
 {
     bool result = Left.Evaluate(entry);
     switch (Conjunction)
     {
         case LogicalConjunction.AND:
             if (result)
                 result = Right.Evaluate(entry);
             break;
         case LogicalConjunction.OR:
             if (!result)
                 result = Right.Evaluate(entry);
             break;
         case LogicalConjunction.XOR:
             result ^= Right.Evaluate(entry);
             break;
     }
     return result;
 }
开发者ID:GitOffice,项目名称:DataPie,代码行数:19,代码来源:ZipFile.Selector.cs


示例8: Main

	public static void Main(string[] args)
	{
		string[] filenames = Directory.GetFiles(args[0]);
		
		Crc32 crc = new Crc32();
		ZipOutputStream s = new ZipOutputStream(File.Create(args[1]));
		
		s.SetLevel(6); // 0 - store only to 9 - means best compression
		
		foreach (string file in filenames) {
			FileStream fs = File.OpenRead(file);
			
			byte[] buffer = new byte[fs.Length];
			fs.Read(buffer, 0, buffer.Length);
			ZipEntry entry = new ZipEntry(file);
			
			entry.DateTime = DateTime.Now;
			
			// set Size and the crc, because the information
			// about the size and crc should be stored in the header
			// if it is not set it is automatically written in the footer.
			// (in this case size == crc == -1 in the header)
			// Some ZIP programs have problems with zip files that don't store
			// the size and crc in the header.
			entry.Size = fs.Length;
			fs.Close();
			
			crc.Reset();
			crc.Update(buffer);
			
			entry.Crc  = crc.Value;
			
			s.PutNextEntry(entry);
			
			s.Write(buffer, 0, buffer.Length);
			
		}
		
		s.Finish();
		s.Close();
	}
开发者ID:xuchuansheng,项目名称:GenXSource,代码行数:41,代码来源:Main.cs


示例9: ZipData

    /// <summary>
    /// Архивирует данные одного потока в другой поток.
    /// </summary>
    /// <param name="inputStream">Входной поток.</param>
    /// <param name="outputStream">Выходной поток.</param>
    /// <param name="entryFileName">Имя файла, которое будет помещено в выходном архиве.</param>
    public static void ZipData( Stream inputStream, Stream outputStream, string entryFileName )
    {
        Crc32 crc = new Crc32();
        ZipOutputStream zipStream = new ZipOutputStream( outputStream );
        // начинаем архивировать
        zipStream.SetLevel( 9 ); // уровень сжатия

        long length = inputStream.Length;
        byte[] buffer = new byte[length];
        inputStream.Read( buffer, 0, buffer.Length );

        ZipEntry entry = new ZipEntry( entryFileName );
        entry.DateTime = DateTime.Now;
        entry.Size = length;
        crc.Reset();
        crc.Update( buffer );
        entry.Crc = crc.Value;

        zipStream.PutNextEntry( entry );

        zipStream.Write( buffer, 0, buffer.Length );

        zipStream.Finish();
    }
开发者ID:Confirmit,项目名称:Portal,代码行数:30,代码来源:ZipHelper.cs


示例10: ExtractEmbeddedZipFile

		/// <summary>
		/// Process a ZIP file that is embedded within the parent ZIP file. Its contents are extracted and turned into 
		/// albums and media objects just like items in the parent ZIP file.
		/// </summary>
		/// <param name="zipFile">A reference to a ZIP file contained within the parent ZIP file. Notice that we don't do
		/// anything with this parameter other than verify that its extension is "ZIP". That's because we actually extract
		/// the file from the parent ZIP file by calling the ExtractMediaObjectFile method, which extracts the file from 
		/// the class-level member variable _zipStream</param>
		/// <param name="parentAlbum">The album that should contain the top-level directories and files found in the ZIP
		/// file.</param>
		private void ExtractEmbeddedZipFile(ZipEntry zipFile, IAlbum parentAlbum)
		{
			#region Validation

			if (Path.GetExtension(zipFile.Name).ToUpperInvariant() != ".ZIP")
			{
				throw new ArgumentException(String.Concat("The zipFile parameter of the method ExtractEmbeddedZipFile in class ZipUtility must be a ZIP file. Instead, it had the file extension ", Path.GetExtension(zipFile.Name), "."));
			}

			if (parentAlbum == null)
			{
				throw new ArgumentNullException("parentAlbum");
			}

			#endregion

			string filepath = Path.Combine(parentAlbum.FullPhysicalPathOnDisk, Guid.NewGuid().ToString("N") + ".config");
			try
			{
				ExtractMediaObjectFile(filepath);
				using (ZipUtility zip = new ZipUtility(this._userName, this._roles))
				{
					this._skippedFiles.AddRange(zip.ExtractZipFile(new FileInfo(filepath).OpenRead(), parentAlbum, true));
				}
			}
			finally
			{
				File.Delete(filepath);
			}
		}
开发者ID:haimon74,项目名称:KanNaim,代码行数:40,代码来源:ZipUtility.cs


示例11: AddMediaObjectToGallery

		/// <summary>
		/// Adds the <paramref name="zipContentFile"/> as a media object to the <paramref name="album"/>.
		/// </summary>
		/// <param name="zipContentFile">A reference to a file in a ZIP archive.</param>
		/// <param name="album">The album to which the file should be added as a media object.</param>
		private void AddMediaObjectToGallery(ZipEntry zipContentFile, IAlbum album)
		{
			string zipFileName = Path.GetFileName(zipContentFile.Name).Trim();

			if (zipFileName.Length == 0)
				return;

			string uniqueFilename = HelperFunctions.ValidateFileName(album.FullPhysicalPathOnDisk, zipFileName);
			string uniqueFilepath = Path.Combine(album.FullPhysicalPathOnDisk, uniqueFilename);

			// Extract the file from the zip stream and save as the specified filename.
			ExtractMediaObjectFile(uniqueFilepath);

			// Get the file we just saved to disk.
			FileInfo mediaObjectFile = new FileInfo(uniqueFilepath);

			try
			{
				IGalleryObject mediaObject = Factory.CreateMediaObjectInstance(mediaObjectFile, album);
				HelperFunctions.UpdateAuditFields(mediaObject, this._userName);
				mediaObject.Save();

				if ((_discardOriginalImage) && (mediaObject is Business.Image))
				{
					((Business.Image)mediaObject).DeleteHiResImage();
					mediaObject.Save();
				}
			}
			catch (ErrorHandler.CustomExceptions.UnsupportedMediaObjectTypeException ex)
			{
				this._skippedFiles.Add(new KeyValuePair<string, string>(mediaObjectFile.Name, ex.Message));
				File.Delete(mediaObjectFile.FullName);
			}
		}
开发者ID:haimon74,项目名称:KanNaim,代码行数:39,代码来源:ZipUtility.cs


示例12: VerifyAlbumExistsAndReturnReference

		private IAlbum VerifyAlbumExistsAndReturnReference(ZipEntry zipContentFile, IAlbum rootParentAlbum)
		{
			// Get the directory path of the next file or directory within the zip file.
			// Ex: album1\album2\album3, album1
			string zipDirectoryPath = Path.GetDirectoryName(zipContentFile.Name);

			string[] directoryNames = zipDirectoryPath.Split(new char[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);

			string albumFullPhysicalPath = rootParentAlbum.FullPhysicalPathOnDisk;
			IAlbum currentAlbum = rootParentAlbum;

			foreach (string directoryNameFromZip in directoryNames)
			{
				string shortenedDirName = GetPreviouslyCreatedTruncatedAlbumName(albumFullPhysicalPath, directoryNameFromZip);

				// Ex: c:\inetpub\wwwroot\galleryserver\mypics\2006\album1
				albumFullPhysicalPath = System.IO.Path.Combine(albumFullPhysicalPath, shortenedDirName);

				IAlbum newAlbum = null;
				if (Directory.Exists(albumFullPhysicalPath))
				{
					// Directory exists, so there is probably an album corresponding to it. Find it.
					IGalleryObjectCollection childGalleryObjects = currentAlbum.GetChildGalleryObjects(GalleryObjectType.Album);
					foreach (IGalleryObject childGalleryObject in childGalleryObjects)
					{
						if (childGalleryObject.FullPhysicalPathOnDisk == albumFullPhysicalPath)
						{
							newAlbum = childGalleryObject as Album; break;
						}
					}

					if (newAlbum == null)
					{
						// No album in the database matches that directory. Add it.

						// Before we add the album, we need to make sure the user has permission to add the album. Check if user
						// is authenticated and if the current album is the one passed into this method. It can be assumed that any
						// other album we encounter has been created by this method and we checked for permission when it was created.
						if (this._isAuthenticated && (currentAlbum.Id == rootParentAlbum.Id))
							SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.AddChildAlbum, this._roles, currentAlbum.Id, this._isAuthenticated, currentAlbum.IsPrivate);

						newAlbum = Factory.CreateAlbumInstance();
						newAlbum.Parent = currentAlbum;
						newAlbum.IsPrivate = currentAlbum.IsPrivate;
						newAlbum.DirectoryName = directoryNameFromZip;
						HelperFunctions.UpdateAuditFields(newAlbum, this._userName);
						newAlbum.Save();
					}
				}
				else
				{
					// The directory doesn't exist. Create an album.

					// Before we add the album, we need to make sure the user has permission to add the album. Check if user
					// is authenticated and if the current album is the one passed into this method. It can be assumed that any
					// other album we encounter has been created by this method and we checked for permission when it was created.
					if (this._isAuthenticated && (currentAlbum.Id == rootParentAlbum.Id))
						SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.AddChildAlbum, this._roles, currentAlbum.Id, this._isAuthenticated, currentAlbum.IsPrivate);

					newAlbum = Factory.CreateAlbumInstance();
					newAlbum.IsPrivate = currentAlbum.IsPrivate;
					newAlbum.Parent = currentAlbum;
					newAlbum.Title = directoryNameFromZip;
					HelperFunctions.UpdateAuditFields(newAlbum, this._userName);
					newAlbum.Save();

					// If the directory name written to disk is different than the name from the zip file, add it to
					// our hash table.
					if (!directoryNameFromZip.Equals(newAlbum.DirectoryName))
					{
						this._albumAndDirectoryNamesLookupTable.Add(Path.Combine(currentAlbum.FullPhysicalPathOnDisk, directoryNameFromZip), Path.Combine(currentAlbum.FullPhysicalPathOnDisk, newAlbum.DirectoryName));
					}

				}
				currentAlbum = newAlbum;
			}

			return currentAlbum;
		}
开发者ID:haimon74,项目名称:KanNaim,代码行数:79,代码来源:ZipUtility.cs


示例13: InitializeAESPassword

		/// <summary>
		/// Initializes encryption keys based on given password.
		/// </summary>
		protected void InitializeAESPassword(ZipEntry entry, string rawPassword,
											out byte[] salt, out byte[] pwdVerifier) {
			salt = new byte[entry.AESSaltLen];
			// Salt needs to be cryptographically random, and unique per file
			if (_aesRnd == null)
				_aesRnd = new RNGCryptoServiceProvider();
			_aesRnd.GetBytes(salt);
			int blockSize = entry.AESKeySize / 8;	// bits to bytes

			cryptoTransform_ = new ZipAESTransform(rawPassword, salt, blockSize, true);
			pwdVerifier = ((ZipAESTransform)cryptoTransform_).PwdVerifier;
		}
开发者ID:jeffmgibson,项目名称:SolidEdgeContrib.Reader,代码行数:15,代码来源:DeflaterOutputStream.cs


示例14: lBtnDownloadAlbum_Click


//.........这里部分代码省略.........
                    objListPhotos = objMisc.GetPhotoImagesList(objPhotos);

                    if ((DownloadPhotoAlbumId > 0) && (objListPhotos.Count > 0))
                    {

                        // zip up the files
                        try
                        {
                            string sTargetFolderPath = getPath[0] + "/" + getPath[1] + "/" + _tributeUrl.Replace(" ", "_") + "_" + _tributeType.Replace(" ", "_");

                            //to create directory for image.
                            string galleryPath = getPath[0] + "/" + getPath[1] + "/" + getPath[6];
                            string sZipFileName = "Album_" + DownloadPhotoAlbumId.ToString();
                            string[] filenames = Directory.GetFiles(sTargetFolderPath);
                            // Zip up the files - From SharpZipLib Demo Code
                            using (ZipOutputStream s = new ZipOutputStream(File.Create(galleryPath + "\\" + sZipFileName + ".zip")))
                            {
                                s.SetLevel(9); // 0-9, 9 being the highest level of compression

                                byte[] buffer = new byte[4096];
                                foreach (Photos objPhoto in objListPhotos)
                                {
                                    bool Foundflag = true;
                                    string ImageFile = string.Empty;
                                    string smallFile = string.Empty;
                                    ImageFile = sTargetFolderPath + "\\" + "/Big_" + objPhoto.PhotoImage;
                                    smallFile = sTargetFolderPath + "\\" + objPhoto.PhotoImage;
                                    foreach (string file in filenames)
                                    {
                                        if ((file.EndsWith("Big_" + objPhoto.PhotoImage)) && (File.Exists(ImageFile)))
                                        {
                                            Foundflag = false; //FlagsAttribute set false for small image
                                            //Code to zip 
                                            ZipEntry entry = new ZipEntry(Path.GetFileName(ImageFile));

                                            entry.DateTime = DateTime.Now;
                                            s.PutNextEntry(entry);

                                            using (FileStream fs = File.OpenRead(ImageFile))
                                            {
                                                int sourceBytes;
                                                do
                                                {
                                                    sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                                    s.Write(buffer, 0, sourceBytes);

                                                } while (sourceBytes > 0);
                                            }
                                            //Code to zip till here 
                                        }
                                    }
                                    if (Foundflag) // if big image is not found.
                                    {
                                        foreach (string file in filenames)
                                        {
                                            if ((file.EndsWith(objPhoto.PhotoImage)) && (File.Exists(smallFile)) && (!(file.EndsWith("Big_" + objPhoto.PhotoImage))))
                                            //(File.Exists(smallFile))
                                            {
                                                ZipEntry entry = new ZipEntry(Path.GetFileName(file));

                                                entry.DateTime = DateTime.Now;
                                                s.PutNextEntry(entry);

                                                using (FileStream fs = File.OpenRead(file))
                                                {
                                                    int sourceBytes;
开发者ID:rupendra-sharma07,项目名称:MainTrunk,代码行数:67,代码来源:Story.master.cs


示例15: ZipAndroidResources

    public static void ZipAndroidResources()
    {
        try
        {
            var filenames = GatherAndroidResourceFiles();

            // 'using' statements guarantee the stream is closed properly which is a big source
            // of problems otherwise.  Its exception safe as well which is great.
            using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(Application.dataPath + "/Android.zip")))
            {

                zipStream.SetLevel(9); // 0 - store only to 9 - means best compression

                byte[] buffer = new byte[4096];

                foreach (string file in filenames)
                {
                    string name = file.Substring(AndroidResourceFolder.Length + 1);
                    ZipEntry entry = new ZipEntry(name);

                    // Setup the entry data as required.

                    // Crc and size are handled by the library for seakable streams
                    // so no need to do them here.

                    // Could also use the last write time or similar for the file.
                    entry.DateTime = System.DateTime.Now;
                    zipStream.PutNextEntry(entry);

                    using (FileStream fileStream = File.OpenRead(file))
                    {

                        // Using a fixed size buffer here makes no noticeable difference for output
                        // but keeps a lid on memory usage.
                        int sourceBytes;
                        do
                        {
                            sourceBytes = fileStream.Read(buffer, 0, buffer.Length);
                            zipStream.Write(buffer, 0, sourceBytes);
                        } while (sourceBytes > 0);
                    }
                }

                // Finish/Close arent needed strictly as the using statement does this automatically

                // Finish is important to ensure trailing information for a Zip file is appended.  Without this
                // the created file would be invalid.
                zipStream.Finish();

                // Close is important to wrap things up and unlock the file.
                zipStream.Close();

                AssetDatabase.Refresh();
            }
        }
        catch (Exception ex)
        {
            Debug.LogError(string.Format("Exception during processing {0}", ex));

            // No need to rethrow the exception as for our purposes its handled.
        }
    }
开发者ID:bennychen,项目名称:build-kit,代码行数:62,代码来源:AndroidResourceEditor.cs


示例16: ExtractFileEntry

		void ExtractFileEntry(ZipEntry entry, string targetName)
		{
			bool proceed = true;
			if ( overwrite_ != Overwrite.Always ) {
				if ( File.Exists(targetName) ) {
					if ( (overwrite_ == Overwrite.Prompt) && (confirmDelegate_ != null) ) {
						proceed = confirmDelegate_(targetName);
					}
					else {
						proceed = false;
					}
				}
			}
			
			if ( proceed ) {
				if ( events_ != null ) {
					continueRunning_ = events_.OnProcessFile(entry.Name);
				}
			
				if ( continueRunning_ ) {
					try {
						using ( FileStream outputStream = File.Create(targetName) ) {
							if ( buffer_ == null ) {
								buffer_ = new byte[4096];
							}
							if ((events_ != null) && (events_.Progress != null))
							{
								StreamUtils.Copy(zipFile_.GetInputStream(entry), outputStream, buffer_,
									events_.Progress, events_.ProgressInterval, this, entry.Name, entry.Size);
							}
							else
							{
								StreamUtils.Copy(zipFile_.GetInputStream(entry), outputStream, buffer_);
							}
							
							if (events_ != null) {
								continueRunning_ = events_.OnCompletedFile(entry.Name);
							}
						}

#if !NETCF_1_0 && !NETCF_2_0
						if ( restoreDateTimeOnExtract_ ) {
							File.SetLastWriteTime(targetName, entry.DateTime);
						}
						
						if ( RestoreAttributesOnExtract && entry.IsDOSEntry && (entry.ExternalFileAttributes != -1)) {
							FileAttributes fileAttributes = (FileAttributes) entry.ExternalFileAttributes;
							// TODO: FastZip - Setting of other file attributes on extraction is a little trickier.
							fileAttributes &= (FileAttributes.Archive | FileAttributes.Normal | FileAttributes.ReadOnly | FileAttributes.Hidden);
							File.SetAttributes(targetName, fileAttributes);
						}
#endif						
					}
					catch(Exception ex) {
						if ( events_ != null ) {
							continueRunning_ = events_.OnFileFailure(targetName, ex);
						}
						else {
                            continueRunning_ = false;
                            throw;
						}
					}
				}
			}
		}
开发者ID:Johnnyfly,项目名称:source20131023,代码行数:65,代码来源:FastZip.cs


示例17: ZipDir

    /// <summary>  
    /// 压缩文件夹的方法  
    /// </summary>  
    /// <param name="DirToZip">被压缩的文件名称(包含文件路径)</param>  
    /// <param name="ZipedFile">压缩后的文件名称(包含文件路径)</param>  
    /// <param name="CompressionLevel">压缩率0(无压缩),9(压缩率最高)</param>  
    public void ZipDir(string DirToZip, string ZipedFile, int CompressionLevel)
    {
        //压缩文件为空时默认与压缩文件夹同一级目录
        if (ZipedFile == string.Empty)
        {
            ZipedFile = DirToZip.Substring(DirToZip.LastIndexOf("/") + 1);
            ZipedFile = DirToZip.Substring(0, DirToZip.LastIndexOf("/")) + "//" + ZipedFile + ".zip";
        }

        if (Path.GetExtension(ZipedFile) != ".zip")
        {
            ZipedFile = ZipedFile + ".zip";
        }

        using (ZipOutputStream zipoutputstream = new ZipOutputStream(File.Create(ZipedFile)))
        {
            zipoutputstream.SetLevel(CompressionLevel);
            Crc32 crc = new Crc32();
            Hashtable fileList = getAllFies(DirToZip);
            foreach (DictionaryEntry item in fileList)
            {
                FileStream fs = File.OpenRead(item.Key.ToString());
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                ZipEntry entry = new ZipEntry(item.Key.ToString().Substring(DirToZip.Length));
                entry.DateTime = (DateTime)item.Value;
                entry.Size = fs.Length;
                fs.Close();
                crc.Reset();
                crc.Update(buffer);
                entry.Crc = crc.Value;
                zipoutputstream.PutNextEntry(entry);
                zipoutputstream.Write(buffer, 0, buffer.Length);
            }
        }
    }
开发者ID:fuhongliang,项目名称:GraduateProject,代码行数:42,代码来源:DIStatementExport.aspx.cs


示例18: ExtractEntry

		void ExtractEntry(ZipEntry entry)
		{
			bool doExtraction = entry.IsCompressionMethodSupported();
			string targetName = entry.Name;
			
			if ( doExtraction ) {
				if ( entry.IsFile ) {
					targetName = extractNameTransform_.TransformFile(targetName);
				}
				else if ( entry.IsDirectory ) {
					targetName = extractNameTransform_.TransformDirectory(targetName);
				}
				
				doExtraction = !((targetName == null) || (targetName.Length == 0));
			}
			
			// TODO: Fire delegate/throw exception were compression method not supported, or name is invalid?

			string dirName = null;
			
			if ( doExtraction ) {
					if ( entry.IsDirectory ) {
						dirName = targetName;
					}
					else {
						dirName = Path.GetDirectoryName(Path.GetFullPath(targetName));
					}
			}
			
			if ( doExtraction && !Directory.Exists(dirName) ) {
				if ( !entry.IsDirectory || CreateEmptyDirectories ) {
					try {
						Directory.CreateDirectory(dirName);
					}
					catch (Exception ex) {
						doExtraction = false;
						if ( events_ != null ) {
							if ( entry.IsDirectory ) {
								continueRunning_ = events_.OnDirectoryFailure(targetName, ex);
							}
							else {
								continueRunning_ = events_.OnFileFailure(targetName, ex);
							}
						}
						else {
							continueRunning_ = false;
                            throw;
						}
					}
				}
			}
			
			if ( doExtraction && entry.IsFile ) {
				ExtractFileEntry(entry, targetName);
			}
		}
开发者ID:Johnnyfly,项目名称:source20131023,代码行数:56,代码来源:FastZip.cs


示例19: CompressFolder

    private void CompressFolder(string path, ZipOutputStream zipStream, int folderOffset)
    {
        string[] files = Directory.GetFiles(path);

        foreach (string filename in files)
        {

            FileInfo fi = new FileInfo(filename);

            string entryName = filename.Substring(folderOffset); // Makes the name in zip based on the folder
            entryName = ZipEntry.CleanName(entryName); // Removes drive from name and fixes slash direction
            ZipEntry newEntry = new ZipEntry(entryName);
            newEntry.DateTime = fi.LastWriteTime; // Note the zip format stores 2 second granularity

            // Specifying the AESKeySize triggers AES encryption. Allowable values are 0 (off), 128 or 256.
            // A password on the ZipOutputStream is required if using AES.
            //   newEntry.AESKeySize = 256;

            // To permit the zip to be unpacked by built-in extractor in WinXP and Server2003, WinZip 8, Java, and other older code,
            // you need to do one of the following: Specify UseZip64.Off, or set the Size.
            // If the file may be bigger than 4GB, or you do not need WinXP built-in compatibility, you do not need either,
            // but the zip will be in Zip64 format which not all utilities can understand.
            //   zipStream.UseZip64 = UseZip64.Off;
            newEntry.Size = fi.Length;

            zipStream.PutNextEntry(newEntry);

            // Zip the file in buffered chunks
            // the "using" will close the stream even if an exception occurs
            byte[] buffer = new byte[4096];
            using (FileStream streamReader = File.OpenRead(filename))
            {
                StreamUtils.Copy(streamReader, zipStream, buffer);
            }
            zipStream.CloseEntry();
        }
        string[] folders = Directory.GetDirectories(path);
        foreach (string folder in folders)
        {
            CompressFolder(folder, zipStream, folderOffset);
        }
    }
开发者ID:BankPatsakorn,项目名称:Betimes,代码行数:42,代码来源:Schema2Excel.aspx.cs


示例20: ZipEntry

	public ZipEntry(ZipEntry e)
	{
	}
开发者ID:calumjiao,项目名称:Mono-Class-Libraries,代码行数:3,代码来源:test-161.cs



注:本文中的ZipEntry类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# ZipFile类代码示例发布时间:2022-05-24
下一篇:
C# ZipArchive类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap