SharpZipLib :https://github.com/icsharpcode/SharpZipLib

C#使用SharpZipLib对文件进行压缩(.rar,.zip)

private MemoryStream DoZip(List<PluginImportModel> contents)
{
	MemoryStream memoryStream = new MemoryStream();
	ZipOutputStream zipOutStream = new ZipOutputStream(memoryStream);
	foreach (var plugin in contents)
	{
		// 压缩包中的文件名
		string fileName = plugin.pluginName + ".yesp";
		ZipEntry entry = new ZipEntry(fileName);
		entry.DateTime = DateTime.Now;
		entry.IsUnicodeText = true;
		zipOutStream.PutNextEntry(entry);

		// 文件中内容
		string content = Newtonsoft.Json.JsonConvert.SerializeObject(plugin);
		//byte[] array = Encoding.ASCII.GetBytes(content);

		// 加密
		byte[] array = Encrypt(content);

		zipOutStream.Write(array, 0, array.Length);
		zipOutStream.CloseEntry();
	}
	//使用流操作时一定要设置IsStreamOwner为false。否则很容易发生在文件流关闭后的异常。
	zipOutStream.IsStreamOwner = false;
	zipOutStream.Finish();
	zipOutStream.Close();

	//byte[] buffer = memoryStream.GetBuffer();
	memoryStream.Seek(0, SeekOrigin.Begin);
	return memoryStream;

}

C#使用SharpZipLib对压缩文件(.rar,.zip)进行解压

/// <summary>
/// 解压文件
/// </summary>
/// <param name="stream"></param>
/// <param name="localPath"></param>
void unZIP(Stream stream, string localPath)
{
	ZipInputStream zipInputStream = new ZipInputStream(stream);
	ZipEntry zipEntryFromZippedFile;
	while ((zipEntryFromZippedFile = zipInputStream.GetNextEntry()) != null)
	{
		if (zipEntryFromZippedFile.IsDirectory)
		{
			string _p = System.IO.Path.Combine(localPath, zipEntryFromZippedFile.Name.Replace("/", "\\"));
			if (!System.IO.Directory.Exists(_p))
				System.IO.Directory.CreateDirectory(_p);
		}
		if (zipEntryFromZippedFile.IsFile)
		{
			byte[] data = new byte[zipInputStream.Length];
			if (zipInputStream.Read(data, 0, data.Length) > 0)
			{
				using (FileStream streamWriter = System.IO.File.Create(System.IO.Path.Combine(localPath, zipEntryFromZippedFile.Name.Replace("/", "\\"))))
				{
					streamWriter.Write(data, 0, data.Length);
				}
			}
		}
	}
	zipInputStream.Close();
}
(adsbygoogle = window.adsbygoogle || []).push({});