开源框架 SharpZipLib 可以压缩与解压缩文件或文件夹为Zip格式的文件。事实上,它还可以压缩文件或文本到指定格式的字符串,从而通过网络高效传输数据。基本思路为:压缩后输出到内存流MemoryStream,然后转成字节数组,最后转换成字符串。解压缩时的顺序则相反。本文探讨压缩为Base64格式的字符串,见如下代码:
public class TZipHelper
{
/// <summary>
/// 压缩单个文件为一个Base64字符串。
/// </summary>
public static string ZipFileToBase64String(string fileName)
{
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
using (MemoryStream ms = new MemoryStream())
using (ZipOutputStream zip = new ZipOutputStream(ms))
{
ZipEntry entry = new ZipEntry(Path.GetFileName(fileName));
zip.PutNextEntry(entry);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fs.Read(buffer, 0, buffer.Length)) > 0)
{