之前在做c#.net项目的时候需要将文件和文件夹进行压缩和解压缩,于是就从网上找了System.IO.Compression.net原生压缩解压库实现。后面接触得多了,发现压缩解压缩的方式不止这一种,原生写法能够压缩解压缩以外还有SharpZipLib也可以实现同样的效果,故在此把这两种压缩解压缩方式示例代码整理了一下,让首次接触压缩和解压缩的朋友可以少走些弯路。我们首先来讲讲System.IO.Compression库压缩解压。首先需要在项目namespace里引用引用System.IO.Compression命名空间。然后封装一下其中的关于压缩和解压缩的类,方便调用,代码如下。本教程例子代码下载地址 CsZipDemo.zip(密码: 7831),完美支持.net framework.net core跨平台使用。
c#压缩解压示例程序

ZipFile压缩解压
ZipFile目前仅支持压缩解压zip格式的压缩包。

/// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="srcPath">源文件文件夹集合</param>
        /// <param name="zipPath">压缩后的zip文件</param>
        /// <returns></returns>
        public static Tuple<bool, string> NativeCompressFile(List<string> srcPath, string zipPath)
        {
            try
            {
                //创建临时目录
                var tmpPath = $"{AppDomain.CurrentDomain.BaseDirectory}{Guid.NewGuid()}_temp";
                if (!Directory.Exists(tmpPath))
                {
                    Directory.CreateDirectory(tmpPath);
                }
                srcPath.ForEach(s =>
                {
                    if (File.Exists(s))
                    {
                        File.Copy(s, $"{tmpPath}\\{Path.GetFileName(s)}");
                    }
                    else if (Directory.Exists(s))
                    {
                        var tmpDir = new DirectoryInfo(s);
                        CopyFolder(s, $"{tmpPath}\\{tmpDir.Name}");
                    }
                });

                System.IO.Compression.ZipFile.CreateFromDirectory(tmpPath, zipPath);
                Directory.Delete(tmpPath, true);
                return new Tuple<bool, string>(true, "OK");
            }
            catch (Exception ex)
            {
                return new Tuple<bool, string>(false, $"压缩文件时出现异常:{ex.Message}");
            }
        }

        /// <summary>
        /// 解压缩文件
        /// </summary>
        /// <param name="zipFileName">要解压的zip文件</param>
        /// <param name="dstDirName">解压目标目录</param>
        /// <returns></returns>
        public static Tuple<bool, string> NativeDecompressFile(string zipFileName, string dstDirName)
        {
            try
            {
                if (!File.Exists(zipFileName))
                {
                    return new Tuple<bool, string>(false, "压缩文件不存在");
                }
                string directoryName = Path.GetDirectoryName(dstDirName);
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }
                System.IO.Compression.ZipFile.ExtractToDirectory(zipFileName, dstDirName);
                return new Tuple<bool, string>(true, "OK");
            }
            catch (Exception ex)
            {
                return new Tuple<bool, string>(false, $"解压文件时出现异常:{ex.Message}");
            }
        }

        /// <summary>
        /// 复制文件夹及文件
        /// </summary>
        /// <param name="sourceFolder">原文件路径</param>
        /// <param name="destFolder">目标文件路径</param>
        /// <returns></returns>
        private static void CopyFolder(string sourceFolder, string destFolder)
        {
            try
            {
                //如果目标路径不存在,则创建目标路径
                if (!Directory.Exists(destFolder))
                {
                    Directory.CreateDirectory(destFolder);
                }
                //得到原文件根目录下的所有文件
                string[] files = Directory.GetFiles(sourceFolder);
                foreach (string file in files)
                {
                    string name = Path.GetFileName(file);
                    string dest = Path.Combine(destFolder, name);
                    // 复制文件
                    File.Copy(file, dest);
                }
                //得到原文件根目录下的所有文件夹
                string[] folders = Directory.GetDirectories(sourceFolder);
                foreach (string folder in folders)
                {
                    string dirName = folder.Split('\\')[folder.Split('\\').Length - 1];
                    string destfolder = Path.Combine(destFolder, dirName);
                    // 递归调用
                    CopyFolder(folder, destfolder);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

SharpZipLib压缩解压
SharpZipLib目前仅支持压缩解压zip格式的压缩包。

/// <summary>
        /// SharpZipLib压缩文件
        /// </summary>
        /// <param name="srcPath">源文件或文件夹</param>
        /// <param name="zipFilePath">压缩后的zip文件</param>
        public static void ZipLibCompressFile(List<string> srcPath, string zipFilePath)
        {
            using (ICSharpCode.SharpZipLib.Zip.ZipFile zip = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(zipFilePath))
            {
                zip.BeginUpdate();
                srcPath.ForEach(s =>
                {
                    if (File.Exists(s))
                    {
                        zip.Add(s);
                    }
                    else if (Directory.Exists(s))
                    {
                        zip.AddDirectory(s);
                    }
                });

                zip.CommitUpdate();
            }
        }

        /// <summary>
        /// SharpZipLib解压缩文件
        /// </summary>
        /// <param name="zipFilePath">源zip压缩包</param>
        /// <param name="dstDirPath"> 解压目录</param>
        public static void ZipLibDecompressFile(string zipFilePath, string dstDirPath)
        {
            (new FastZip()).ExtractZip(zipFilePath, dstDirPath, string.Empty);
        }

        /// <summary>
        /// SharpZipLib附加文件文件夹
        /// </summary>
        /// <param name="zipFilePath"> 源zip压缩包</param>
        /// <param name="appendPath"> 附加的文件、文件夹路径集合</param>
        public static void ZipLibAppendObj(string zipFilePath, List<string> appendPath)
        {
            using (ICSharpCode.SharpZipLib.Zip.ZipFile zip = new ICSharpCode.SharpZipLib.Zip.ZipFile(zipFilePath))
            {
                zip.BeginUpdate();
                appendPath.ForEach(s =>
                {
                    if (File.Exists(s))
                    {
                        zip.Add(s);
                    }
                    else if (Directory.Exists(s))
                    {
                        zip.AddDirectory(s);
                    }
                });

                zip.CommitUpdate();
            }
        }

        /// <summary>
        /// SharpZipLib删除压缩包内文件文件夹
        /// </summary>
        /// <param name="zipFilePath">源zip压缩包</param>
        /// <param name="deletePath"> 要删除的压缩包内文件、文件夹路径集合 </param>
        public static void ZipLibDeleteObj(string zipFilePath, List<string> deletePath)
        {
            using (ICSharpCode.SharpZipLib.Zip.ZipFile zip = new ICSharpCode.SharpZipLib.Zip.ZipFile(zipFilePath))
            {
                zip.BeginUpdate();
                deletePath.ForEach(s =>
                {
                    if (zip.FindEntry(s, false) >= 0)
                    {
                        zip.Delete(s);
                    }
                });

                zip.CommitUpdate();
            }
        }

        /// <summary>
        /// SharpZipLib查看压缩包内文件
        /// </summary>
        /// <param name="zipFilePath"> 源zip压缩包 </param
        public static List<string> ZipLibViewObj(string zipFilePath)
        {
            var list = new List<string>();
            using (ICSharpCode.SharpZipLib.Zip.ZipFile zip = new ICSharpCode.SharpZipLib.Zip.ZipFile(zipFilePath))
            {
                foreach (ZipEntry entry in zip)
                {
                    list.Add(entry.Name);
                }
            }
            return list;
        }
最后修改:2022 年 10 月 10 日
免责声明:本站为个人博客,博客所发布的一切修改补丁、注册机和注册信息及软件的文章仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途。否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。访问和下载本站内容,说明您已同意上述条款。