⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sz.cs

📁 C#的zip的源代码
💻 CS
📖 第 1 页 / 共 3 页
字号:
		
			if (names.Length == 0 && addEmptyDirectoryEntries) {
				AddFolder(basePath);
				++result;
			}
		
			if (recursive) {
				names = Directory.GetDirectories(basePath);
				foreach (string folderName in names) {
					result += CompressFolder(folderName, recursive, searchPattern);
				}
			}
			return result;
		}
	
		/// <summary>
		/// Create archives based on specifications passed and internal state
		/// </summary>		
		void Create(ArrayList fileSpecs)
		{
			string zipFileName = fileSpecs[0] as string;
			if (Path.GetExtension(zipFileName).Length == 0) {
				zipFileName = Path.ChangeExtension(zipFileName, ".zip");
			}
			
			fileSpecs.RemoveAt(0);

			if (overwriteFiles == Overwrite.Never && File.Exists(zipFileName)) {
				System.Console.WriteLine("File {0} already exists", zipFileName);
				return;
			}

			int totalEntries = 0;
			
			using (FileStream stream = File.Create(zipFileName)) {
				using (outputStream = new ZipOutputStream(stream)) {
					if (password != null && password.Length > 0) {
						outputStream.Password = password;
					}

					outputStream.UseZip64 = useZip64_;
					outputStream.SetLevel(compressionLevel);
					foreach(string spec in fileSpecs) {
						string fileName = Path.GetFileName(spec);
						string pathName = Path.GetDirectoryName(spec);
						
						if (pathName == null || pathName.Length == 0) {
							pathName = Path.GetFullPath(".");
							if (relativePathInfo == true) {
								removablePathPrefix = pathName;
							}
						} else {
							pathName = Path.GetFullPath(pathName);
							// TODO: for paths like ./txt/*.txt the prefix should be fullpath for .
							// for z:txt/*.txt should be fullpath for z:.
							if (relativePathInfo == true) {
								removablePathPrefix = pathName;
							}
						}
						
						
						// TODO wildcards arent full supported by this
						if (recursive || fileName.IndexOf('*') >= 0 || fileName.IndexOf('?') >= 0) {
							
							// TODO this allows possible conflicts in filenames that are added to Zip file
							// as part of different file specs.
							totalEntries += CompressFolder(pathName, recursive, fileName);
						} else {
							AddFile(pathName + @"\" + fileName);
							++totalEntries;
						}
					}
					
					if (totalEntries == 0) {
						Console.WriteLine("File created has no entries!");
					}
				}
			}
		}

		bool ExtractFile(ZipInputStream inputStream, ZipEntry theEntry, string targetDir)
		{
			// try and sort out the correct place to save this entry
			string entryFileName;
						
			if (Path.IsPathRooted(theEntry.Name)) 
			{
				string workName = Path.GetPathRoot(theEntry.Name);
				workName = theEntry.Name.Substring(workName.Length);
				entryFileName = Path.Combine(Path.GetDirectoryName(workName), Path.GetFileName(theEntry.Name));
			} 
			else 
			{
				entryFileName = theEntry.Name;
			}

			string targetName = Path.Combine(targetDir, entryFileName);
						
			string fullPath = Path.GetDirectoryName(Path.GetFullPath(targetName));
#if TEST
			Console.WriteLine("Decompress targetfile name " + entryFileName);
			Console.WriteLine("Decompress targetpath " + fullPath);
#endif						
						
			// Could be an option or parameter to allow failure or try creation
			if (Directory.Exists(fullPath) == false)
			{
				try 
				{
					Directory.CreateDirectory(fullPath);
				}
				catch 
				{
					return false;
				}
			} 
			else if (overwriteFiles == Overwrite.Prompt) 
			{
				if (File.Exists(targetName) == true) 
				{
					Console.Write("File " + targetName + " already exists.  Overwrite? ");
								
					// TODO sort out the complexities of Read so single key presses can be used
					string readValue;
					try 
					{
						readValue = Console.ReadLine();
					}
					catch 
					{
						readValue = null;
					}
								
					if (readValue == null || readValue.ToLower() != "y") 
					{
#if TEST
						Console.WriteLine("Skipped!");
#endif						
						return true;
					}
				}
			}
		
					
			if (entryFileName.Length > 0) 
			{
#if TEST
				Console.WriteLine("Extracting...");
#endif						
				using (FileStream streamWriter = File.Create(targetName))
				{
					byte[] data = new byte[4096];
					int size;
					
					do 
					{
						size = inputStream.Read(data, 0, data.Length);
						streamWriter.Write(data, 0, size);
					} while (size > 0);
				}
#if !NETCF
				if (restoreDateTime) 
				{
					File.SetLastWriteTime(targetName, theEntry.DateTime);
				}
#endif
			}
			return true;
		}

		void ExtractDirectory(ZipInputStream inputStream, ZipEntry theEntry, string targetDir)
		{
			// For now do nothing.
		}

		/// <summary>
		/// Decompress a file
		/// </summary>
		/// <param name="fileName">File to decompress</param>
		/// <param name="targetDir">Directory to create output in</param>
		/// <returns>true iff all has been done successfully</returns>
		bool DecompressFile(string fileName, string targetDir)
		{
			bool result = true;
		
	
			try {
				using (ZipInputStream inputStream = new ZipInputStream(File.OpenRead(fileName))) {
					if (password != null) {
						inputStream.Password = password;
					}
		
					ZipEntry theEntry;
		
					while ((theEntry = inputStream.GetNextEntry()) != null) {
						if ( theEntry.IsFile )
						{
							ExtractFile(inputStream, theEntry, targetDir);
						}
						else if ( theEntry.IsDirectory )
						{
							ExtractDirectory(inputStream, theEntry, targetDir);
						}
					}
				}
			}
			catch (Exception except) {
				result = false;
				Console.WriteLine(except.Message + " Failed to unzip file");
			}
		
			return result;
		}
		
		/// <summary>
		/// Extract archives based on user input
		/// Allows simple wildcards to specify multiple archives
		/// </summary>
		void Extract(ArrayList fileSpecs)
		{
			if (targetOutputDirectory == null || targetOutputDirectory.Length == 0) {
				targetOutputDirectory = @".\";
			}
			
			foreach(string spec in fileSpecs) {
				
				string [] names;
				if (spec.IndexOf('*') >= 0 || spec.IndexOf('?') >= 0) {
					string pathName = Path.GetDirectoryName(spec);
					
					if (pathName == null || pathName.Length == 0) {
						pathName = @".\";
					}
					names = Directory.GetFiles(pathName, Path.GetFileName(spec));
				} else {
					names = new string[] { spec };
				}

				foreach (string fileName in names) {				
					if (File.Exists(fileName) == false) {
						Console.WriteLine("No such file exists {0}", spec);
					} else {
						DecompressFile(fileName, targetOutputDirectory);
					}
				}
			}
		}

		void Test(ArrayList fileSpecs)
		{
			string zipFileName = fileSpecs[0] as string;
			if (Path.GetExtension(zipFileName).Length == 0) 
			{
				zipFileName = Path.ChangeExtension(zipFileName, ".zip");
			}

			using (ZipFile zipFile = new ZipFile(zipFileName))
			{
				if ( zipFile.TestArchive(testData) )
				{
					Console.WriteLine("Archive test passed");
				}
				else
				{
					Console.WriteLine("Archive test failure");
				}
			}
		}

		/// <summary>
		/// Delete entries from an archive
		/// </summary>
		/// <param name="fileSpecs">The file specs to operate on.</param>
		void Delete(ArrayList fileSpecs)
		{
			string zipFileName = fileSpecs[0] as string;
			if (Path.GetExtension(zipFileName).Length == 0) 
			{
				zipFileName = Path.ChangeExtension(zipFileName, ".zip");
			}

			using (ZipFile zipFile = new ZipFile(zipFileName))
			{
				zipFile.BeginUpdate();
				for ( int i = 1; i < fileSpecs.Count; ++i )
				{
					zipFile.Delete((string)fileSpecs[i]);
				}
				zipFile.CommitUpdate();
			}
		}

		void Add(ArrayList fileSpecs)
		{
			string zipFileName = fileSpecs[0] as string;
			if (Path.GetExtension(zipFileName).Length == 0) 
			{
				zipFileName = Path.ChangeExtension(zipFileName, ".zip");
			}

			using (ZipFile zipFile = new ZipFile(zipFileName))
			{
				zipFile.BeginUpdate();
				for ( int i = 1; i < fileSpecs.Count; ++i )
				{
					zipFile.Add((string)fileSpecs[i]);
				}
				zipFile.CommitUpdate();
			}
		}

		/// <summary>
		/// Parse command line arguments and 'execute' them.
		/// </summary>		
		void Execute(string[] args) {
			if (SetArgs(args)) {
				if (fileSpecs.Count == 0) {
					if (silent == false) {
						Console.WriteLine("Nothing to do");
					}
				}
				else {
					switch (operation) {
						case Operation.List:
							List(fileSpecs);
							break;
						
						case Operation.Create:
							Create(fileSpecs);
							break;
						
						case Operation.Extract:
							Extract(fileSpecs);
							break;

						case Operation.Delete:
							Delete(fileSpecs);
							break;

						case Operation.Add:
							Add(fileSpecs);
							break;

						case Operation.Test:
							Test(fileSpecs);
							break;
					}
				}
			} else {
				if (silent == false) {
					ShowHelp();
				}
			}
		}
		
		/// <summary>
		/// Entry point for program, creates archiver and runs it
		/// </summary>
		/// <param name="args">
		/// Command line argument to process
		/// </param>
		public static void Main(string[] args) {
		
			SharpZipArchiver sza = new SharpZipArchiver();
			sza.Execute(args);
		}

		#region Instance Fields
		/// <summary>
		/// The Zip64 extension use to apply.
		/// </summary>
		UseZip64 useZip64_ = UseZip64.Off;
		
		/// <summary>
		/// Has user already seen help output?
		/// </summary>
		bool seenHelp;
		
		/// <summary>
		/// The size of the buffer to use when copying.
		/// </summary>
		int bufferSize_ = 8192;

		/// <summary>
		/// Buffer for use when copying between streams.
		/// </summary>
		byte[] buffer;
		
		/// <summary>
		/// File specification possibly with wildcards from command line
		/// </summary>
		ArrayList fileSpecs = new ArrayList();
		
		/// <summary>
		/// Deflate compression level
		/// </summary>
		int compressionLevel = Deflater.DEFAULT_COMPRESSION;
		
		/// <summary>
		/// Create entries for directories with no files
		/// </summary>
		bool addEmptyDirectoryEntries;
		
		/// <summary>
		/// Apply operations recursively
		/// </summary>
		bool recursive;

		/// <summary>
		/// Use ZipFile class for listing entries
		/// </summary>
		bool useZipFileWhenListing;
		
		/// <summary>
		/// Use relative path information
		/// </summary>
		bool relativePathInfo = true;
		
		/// <summary>
		/// Operate silently
		/// </summary>
		bool silent;
		
		/// <summary>
		/// Use store rather than deflate when adding files, not likely to be used much
		/// but it does exercise the option as the library supports it
		/// </summary>
		bool useZipStored;
		
#if !NETCF
		/// <summary>
		/// Restore file date and time to that stored in zip file on extraction
		/// </summary>
		bool restoreDateTime;
#endif

		/// <summary>
		/// Overwrite files handling
		/// </summary>
		Overwrite overwriteFiles = Overwrite.Prompt;

		/// <summary>
		/// Optional password for archive
		/// </summary>
		string password;
		
		/// <summary>
		/// prefix to remove when creating relative path names
		/// </summary>
		string removablePathPrefix;
		
		/// <summary>
		/// Where things will go
		/// </summary>
		string targetOutputDirectory;

		/// <summary>
		/// What to do based on parsed command line arguments
		/// </summary>
		Operation operation = Operation.List;

		/// <summary>
		/// Flag indicating wether entry data should be included when testing.
		/// </summary>
		bool testData;

		/// <summary>
		/// stream used when creating archives.
		/// </summary>
		ZipOutputStream outputStream;

		#endregion
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -