C#使用SharpZipLib进行压缩文件(*.rar,*.zip)操作,压缩和解压


C#使用SharpZipLib进行压缩文件(*.rar,*.zip)操作,压缩和解压

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

C# 全选
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)进行解压

C# 全选
/// <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)
		{
			//var _extension = Path.GetExtension(zipEntryFromZippedFile.Name);
			//if (_extension.ToLower() != ".yesp") continue;

			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();
}
版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
管理员
上一篇:自己创造一个格式,自定义文件后缀名
下一篇:C# 利用SharpZipLib对*.rar压缩文件解压报错
评论列表

发表评论

评论内容
昵称:
关联文章

YES-CMS内容管理系统 售价

联系我们
联系电话:15090125178(微信同号)
电子邮箱:garson_zhang@163.com
站长微信二维码
微信二维码