使用C#压缩解压zip格式文件

在C#.NET中压缩解压zip文件

zip是一种免费开源的压缩格式,windows平台自带zip压缩和解压工具,由于算法是开源的,所以基于zip的解压缩开源库也很多,SharpZipLib是一个很不错的C#库,它能够解压缩zip、gzip和tar格式的文件,首先下载SharpZipLib解压后,在您的项目中引用ICSharpCode.SharpZLib.dll程序集即可,下面是一些关于SharpZipLib压缩和解压的示例。

以下是使用Unity写的ZIP文件的压缩和解压的代码示例:

using UnityEngine;
using System;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Linq;
using System.Collections;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;

public class ZipClass
{
	/// 
	/// 压缩单个文件
	/// 
	/// 需要压缩的文件
	/// 压缩后的文件(初始时不存在)
	/// 压缩级别
	/// 每次写入的内存大小
	public void ZipFile(string FileToZip, string ZipedFile, int CompressionLevel, int BlockSize)
	{
		// 如果文件没有找到,则报错
		if (!File.Exists (FileToZip)) 
		{
			throw new FileNotFoundException ("The specified file" + FileToZip + "could not be found. Zipping aborderd.");
		}

		string fileName = Path.GetFileName (FileToZip);      // 文件名

		Encoding gbk = Encoding.GetEncoding ("gbk");      // 防止中文名乱码
		ICSharpCode.SharpZipLib.Zip.ZipConstants.DefaultCodePage = gbk.CodePage;    

		FileStream streamToZip = new FileStream(FileToZip, FileMode.Open, FileAccess.Read); // 读取需压缩的文件

		FileStream ZipFile = File.Create(ZipedFile);                // 创建压缩文件
		ZipOutputStream ZipStream = new ZipOutputStream(ZipFile);
		ZipEntry ZipEntry = new ZipEntry (fileName);
		ZipStream.PutNextEntry(ZipEntry);
		ZipStream.SetLevel(CompressionLevel);             // 设置压缩级别

		byte[] buffer = new byte[BlockSize];                      
		int size = streamToZip.Read(buffer, 0, buffer.Length);    // 每次读入指定大小
		ZipStream.Write(buffer, 0, size);
		Debug.Log (fileName);
		Debug.Log (size+"----"+ streamToZip.Length);        // 输入当前一次写入的内容大小和当前文件的总大小(字节)

		try
		{
			while (size < streamToZip.Length)       // 保证文件被全部写入
			{
				int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);
				ZipStream.Write(buffer, 0, sizeRead);
				size += sizeRead;
			}
		}
		catch(Exception ex)
		{
			throw ex;
		}
			
		ZipStream.Finish();
		ZipStream.Close();
		streamToZip.Close();
	}


	/// 
	/// 将整个文件夹进行压缩
	/// 
	/// Arguments.
	public void ZipFileMain(string[] args)
	{
		string[] filenames = Directory.GetFiles(args[0]);    // 获取指定的文件夹

		Crc32 crc = new Crc32();
		ZipOutputStream s = new ZipOutputStream(File.Create(args[1]));    //  压缩后的ZIP文件

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

		Encoding gbk = Encoding.GetEncoding ("gbk");      // 防止中文名乱码
		ICSharpCode.SharpZipLib.Zip.ZipConstants.DefaultCodePage = gbk.CodePage;   

		foreach (string file in filenames) 
		{
			//打开压缩文件
			FileStream fs = File.OpenRead(file);
			byte[] buffer = new byte[fs.Length];
			fs.Read(buffer, 0, buffer.Length);
			string fileName = Path.GetFileName (file);      // 文件名
			ZipEntry entry = new ZipEntry(fileName);

			Debug.Log (buffer.Length + "---" + 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();
	}

}


public class UnZipClass
{
	/// 
	/// 解压ZIP
	/// 
	/// 要解压的ZIP文件和解压后保存到的文件夹
	public void UnZip(string[] args)
	{
		ZipInputStream s = new ZipInputStream(File.OpenRead(args[0]));  // 获取要解压的ZIP文件

		Encoding gbk = Encoding.GetEncoding ("gbk");      // 防止中文名乱码
		ICSharpCode.SharpZipLib.Zip.ZipConstants.DefaultCodePage = gbk.CodePage;   

		ZipEntry theEntry;
		while ((theEntry = s.GetNextEntry()) != null) 
		{
			string directoryName = Path.GetDirectoryName(args[1]);   // 获取解压后保存到的文件夹
			string fileName = Path.GetFileName(theEntry.Name);

			//生成解压目录
			Directory.CreateDirectory(directoryName);

			if (fileName != String.Empty) 
			{   
				//解压文件到指定的目录
				FileStream streamWriter = File.Create(args[1]+theEntry.Name);

				int size = 2048;
				byte[] data = new byte[2048];
				while (true)       //  循环写入单个文件
				{
					size = s.Read(data, 0, data.Length);    
					if (size > 0) 
					{
						streamWriter.Write(data, 0, size);     // 每次写入的文件大小
					} 
					else 
					{
						break;
					}
				}

				streamWriter.Close();
			}
		}
		s.Close();
	}
}

public class ZIP : MonoBehaviour {

	// Use this for initialization
	void Start () {
	//	Compression ();    // 压缩
		Decompress();     // 解压
	}

	/// 
	/// 压缩单个文件
	/// 
	void SingleFileCompress()
	{
		string s1 = "D:\\RAR\\Result\\12\\image.jpg"; // //待压缩文件
		string s2 = "D:\\RAR\\Result\\c.zip";       //压缩后的目标文件
		ZipClass zip = new ZipClass ();
		zip.ZipFile (s1, s2, 6, 10);
	}
		
	/// 
	/// 将整个文件夹压缩成zip
	/// 
	void MultiFilesCompress()
	{
		string p1 = "D:\\RAR\\Result\\12";    // //待压缩文件目录
		string p2 = "D:\\RAR\\Result\\a.zip";   //压缩后的目标文件
		string[] FileProperties = new string[2];
		FileProperties [0] = p1;
		FileProperties [1] = p2;
		ZipClass Zc = new ZipClass ();
		Zc.ZipFileMain (FileProperties);
	}


	void Compression()   // 压缩
	{
//		SingleFileCompress ();  // 将单个文件压缩成zip
//		MultiFilesCompress ();  // 将整个文件夹压缩成zip
	}

	void Decompress()    // 解压
	{
		string p1 = "D:\\RAR\\Result\\a.zip";   //待解压的文件
		string p2 = "D:\\RAR\\Result\\11\\";//解压后放置的目标目录
		string []FileProperties=new string[2];
		FileProperties[0]= p1;
		FileProperties[1]= p2;
		UnZipClass UnZc=new UnZipClass();
		UnZc.UnZip(FileProperties);
	}

}



你可能感兴趣的:(文件操作)