【代码片段】压缩和解压缩

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;
using System.Collections;
using ICSharpCode.SharpZipLib.Checksums;
using QuickEAS.CoreLib.Utils;

namespace QuickEAS.CoreLib
{
    public class LibZipWrapper
    {
        public static string Compress(string str)
        {
            //因输入的字符串不是Base64所以转换为Base64,因为HTTP如果不传递Base64则会发生http 400错误
            return Convert.ToBase64String(Compress(Convert.FromBase64String(Convert.ToBase64String(Encoding.Default.GetBytes(str)))));
        }

        public static string Decompress(string str)
        {
            return Encoding.Default.GetString(Decompress(Convert.FromBase64String(str)));
        }

        public static byte[] Compress(byte[] bytes)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                GZipStream Compress = new GZipStream(ms, CompressionMode.Compress);
                Compress.Write(bytes, 0, bytes.Length);
                Compress.Close();
                return ms.ToArray();
            }
        }

        public static byte[] Decompress(Byte[] bytes)
        {
            using (MemoryStream tempMs = new MemoryStream())
            {
                using (MemoryStream ms = new MemoryStream(bytes))
                {
                    GZipStream Decompress = new GZipStream(ms, CompressionMode.Decompress);
                    Decompress.CopyTo(tempMs);
                    Decompress.Close();
                    return tempMs.ToArray();
                }
            }
        }
        /// <summary>压缩文件</summary>
        /// <param name="fileName">被压缩的文件</param>
        /// <param name="zipFileName">压缩后文件名称</param>
        /// <param name="password">压缩文件密码</param>
        public static void ZipFile(string fileName, string zipFileName, string password)
        {
            if (LibSysUtils.FileExists(fileName))
            {
                Crc32 crc = new Crc32();
                ZipOutputStream s = new ZipOutputStream(File.Create(zipFileName));
                try
                {
                    s.Password = password;
                    s.SetLevel(6); // 0 - store only to 9 - means best compression
                    //定义
                    FileInfo fileInfo = new FileInfo(fileName);
                    using (FileStream fs = File.OpenRead(fileInfo.FullName))
                    {
                        try
                        {
                            byte[] buffer = new byte[fs.Length];
                            fs.Read(buffer, 0, buffer.Length);
                            ZipEntry entry = new ZipEntry(fileInfo.FullName);
                            entry.DateTime = DateTime.Now;
                            entry.Size = fs.Length;
                            crc.Reset();
                            crc.Update(buffer);
                            entry.Crc = crc.Value;
                            s.PutNextEntry(entry);
                            s.Write(buffer, 0, buffer.Length);
                        }
                        finally
                        {
                            fs.Close();
                        }
                    }
                    s.Finish();
                }
                finally
                {
                    s.Close();
                }
            }
        }
        /// <summary>解压文件</summary>
        /// <param name="zipFileName">被解压文件名称</param>
        /// <param name="destPath">解压后文件目录</param>
        /// <param name="zipFilePassword">压缩文件密码</param>
        public static void UnZipFile(string zipFileName, string destPath, string zipFilePassword = "")
        {
            ZipInputStream s = new ZipInputStream(File.OpenRead(zipFileName));
            try
            {
                s.Password = zipFilePassword;
                ZipEntry theEntry;
                ArrayList al = new ArrayList();
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    if (theEntry.IsDirectory)
                    {
                        string destEntryPath = LibSysUtils.CombinPath(destPath, LibSysUtils.ReplaceStr(theEntry.Name, "/", @"\"));
                        if (!LibSysUtils.PathExists(destEntryPath))
                            LibSysUtils.CreatePath(destEntryPath);
                    }
                    else
                    {
                        string fileName = LibSysUtils.ReplaceStr(theEntry.Name, "/", @"\");
                        if (fileName != "")
                        {
                            fileName = LibSysUtils.CombinPath(destPath, fileName);
                            if (!LibSysUtils.PathExists(destPath))
                            {
                                LibSysUtils.CreatePath(destPath);
                            }
                            string filePath = Path.GetDirectoryName(fileName);
                            if (!LibSysUtils.PathExists(filePath))
                            {
                                LibSysUtils.CreatePath(filePath);
                            }
                            FileStream streamWriter = File.Create(fileName);
                            try
                            {
                                int size = 2048;
                                byte[] data = new byte[2048];
                                s.Password = "";
                                while (true)
                                {
                                    size = s.Read(data, 0, data.Length);
                                    if (size > 0)
                                    {
                                        streamWriter.Write(data, 0, size);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                            finally
                            {
                                streamWriter.Close();
                            }
                        }
                    }
                }
            }
            finally
            {
                s.Close();
            }
        }
        /// <summary>
        /// 压缩多层目录
        /// </summary>
        /// <param name="path">The directory.</param>
        /// <param name="zipFileName">The ziped file.</param>
        public static void ZipPath(string path, string zipFileName)
        {
            using (System.IO.FileStream zipFile = System.IO.File.Create(zipFileName))
            {
                using (ZipOutputStream s = new ZipOutputStream(zipFile))
                {
                    ZipSetp(path, s, "");
                }
            }
        }
        /// <summary>
        /// 递归遍历目录
        /// </summary>
        /// <param name="strDirectory">The directory.</param>
        /// <param name="s">The ZipOutputStream Object.</param>
        /// <param name="parentPath">The parent path.</param>
        private static void ZipSetp(string strDirectory, ZipOutputStream s, string parentPath)
        {
            if (strDirectory[strDirectory.Length - 1] != Path.DirectorySeparatorChar)
            {
                strDirectory += Path.DirectorySeparatorChar;
            }
            Crc32 crc = new Crc32();

            string[] filenames = Directory.GetFileSystemEntries(strDirectory);

            foreach (string file in filenames)// 遍历所有的文件和目录
            {

                if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
                {
                    string pPath = parentPath;
                    pPath += file.Substring(file.LastIndexOf("\\") + 1);
                    pPath += "\\";
                    ZipSetp(file, s, pPath);
                }

                else // 否则直接压缩文件
                {
                    //打开压缩文件
                    using (FileStream fs = File.OpenRead(file))
                    {
                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);

                        string fileName = parentPath + file.Substring(file.LastIndexOf("\\") + 1);
                        ZipEntry entry = new ZipEntry(fileName);

                        entry.DateTime = DateTime.Now;
                        entry.Size = fs.Length;

                        fs.Close();

                        crc.Reset();
                        crc.Update(buffer);

                        entry.Crc = crc.Value;
                        s.PutNextEntry(entry);

                        s.Write(buffer, 0, buffer.Length);
                    }
                }
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值