WPF文件压缩

时间:2022-07-23
本文章向大家介绍WPF文件压缩,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

文件压缩

添加依赖

Install-Package ICSharpCode.SharpZipLib.dll -Version 0.85.4.369

工具类

using System;
using System.IO;

using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;

namespace SchoolClient.Utils
{
    /// <summary>
    /// Zip 压缩文件
    /// </summary>
    public class ZZip
    {
        public ZZip()
        {
        }

        #region 加压方法

        /// <summary>
        /// 功能:压缩文件(暂时只压缩文件夹下一级目录中的文件,文件夹及其子级被忽略)
        /// </summary>
        /// <param name="dirPath">被压缩的文件夹夹路径</param>
        /// <param name="zipFilePath">生成压缩文件的路径,为空则默认与被压缩文件夹同一级目录,名称为:文件夹名+.zip</param>
        /// <param name="err">出错信息</param>
        /// <returns>是否压缩成功</returns>
        public static void ZipFile(string dirPath, string zipFilePath)
        {
            ZipOutputStream outstream = new ZipOutputStream(File.Create(zipFilePath));
            outstream.SetLevel(6);
            ZipCompress(dirPath, outstream, zipFilePath);
            if (outstream != null)
            {
                outstream.Finish();
                outstream.Close();
            }
        }

        public static void ZipCompress(string strFile, ZipOutputStream outstream, string staticFile)
        {
            if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar)
            {
                strFile += Path.DirectorySeparatorChar;
            }
            DirectoryInfo di = new DirectoryInfo(strFile);
            if (di.Exists)
            {
                Crc32 crc = new Crc32();
                //获取指定目录下所有文件和子目录文件名称
                string[] filenames = Directory.GetFileSystemEntries(strFile);
                //遍历文件
                foreach (string file in filenames)
                {
                    if (Directory.Exists(file))
                    {
                        ZipCompress(file, outstream, staticFile);
                    }
                    //否则,直接压缩文件
                    else
                    {
                        //打开文件
                        FileStream fs = File.OpenRead(file);
                        //定义缓存区对象
                        byte[] buffer = new byte[fs.Length];
                        //通过字符流,读取文件
                        fs.Read(buffer, 0, buffer.Length);
                        //得到目录下的文件(比如:D:Debug1test),test
                        string tempfile = file.Substring(staticFile.LastIndexOf("\") + 1);
                        ZipEntry entry = new ZipEntry(tempfile);
                        entry.DateTime = DateTime.Now;
                        entry.Size = fs.Length;
                        fs.Close();
                        crc.Reset();
                        crc.Update(buffer);
                        entry.Crc = crc.Value;
                        outstream.PutNextEntry(entry);
                        //写文件
                        outstream.Write(buffer, 0, buffer.Length);
                    }
                }
            }
        }

        #endregion 加压方法

        #region 解压

        /// <summary>
        /// 功能:解压zip格式的文件。
        /// </summary>
        /// <param name="zipFilePath">压缩文件路径</param>
        /// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param>
        /// <param name="err">出错信息</param>
        /// <returns>解压是否成功</returns>
        public static bool UnZipFile(string zipFilePath, string unZipDir, out string err)
        {
            err = "";
            if (zipFilePath == string.Empty)
            {
                err = "压缩文件不能为空!";
                return false;
            }
            if (!File.Exists(zipFilePath))
            {
                err = "压缩文件不存在!";
                return false;
            }
            //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹
            if (unZipDir == string.Empty)
                unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));
            if (!unZipDir.EndsWith("//"))
                unZipDir += "//";
            if (!Directory.Exists(unZipDir))
                Directory.CreateDirectory(unZipDir);

            try
            {
                using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
                {
                    ZipEntry theEntry;
                    while ((theEntry = s.GetNextEntry()) != null)
                    {
                        string directoryName = Path.GetDirectoryName(theEntry.Name);
                        string fileName = Path.GetFileName(theEntry.Name);
                        if (directoryName.Length > 0)
                        {
                            Directory.CreateDirectory(unZipDir + directoryName);
                        }
                        if (!directoryName.EndsWith("//"))
                            directoryName += "//";
                        if (fileName != String.Empty)
                        {
                            using (FileStream streamWriter = File.Create(unZipDir + 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;
                                    }
                                }
                            }
                        }
                    }//while
                }
            }
            catch (Exception ex)
            {
                err = ex.Message;
                return false;
            }
            return true;
        }//解压结束

        #endregion 解压
    }
}

调用

ZZip.ZipFile(path, zipPath);