C# 将多个文件打包成压缩包

/*************************************
*  功    能:文件处理工具类.
*  创 建 人:35
*  创建时间:2024-09-12
* ***********************************/

using System.IO.Compression;

namespace Service.Common.Util
{
    public class FileUtil
    {
        
        /// <summary>
        /// 创建文件的压缩包
        /// </summary>
        /// <param name="zipPath">压缩包输出存放路径.</param>
        /// <param name="filePaths">需要压缩的文件路径集合.</param>

       public static void CreateZipFile(string zipPath, string[] filePaths)
        {
            // 确保ZIP压缩包的目标目录存在  
            Directory.CreateDirectory(Path.GetDirectoryName(zipPath));

            // 使用ZipFile.CreateFromDirectory方法时,我们实际上需要创建一个临时目录  
            // 来存放要压缩的文件,但这里我们直接压缩文件列表,所以不需要  
            // 但由于CreateFromDirectory更适合文件夹压缩,我们下面用另一种方法  

            // 对于直接压缩文件列表,我们可以使用ZipArchive和FileStream  
            using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Create))
            {
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
                {
                    foreach (string filePath in filePaths)
                    {
                        // 确保文件存在  
                        if (File.Exists(filePath))
                        {
                            // 获取文件名(不包含路径)  
                            string fileName = Path.GetFileName(filePath);

                            // 创建ZIP条目并添加到压缩包中  
                            ZipArchiveEntry readMeEntry = archive.CreateEntry(fileName);

                            // 使用文件流读取文件内容,并将其写入ZIP条目  
                            using (FileStream streamToCompress = File.OpenRead(filePath))
                            {
                                using (Stream entryStream = readMeEntry.Open())
                                {
                                    streamToCompress.CopyTo(entryStream);
                                }
                            }
                        }
                    }
                }
            }
        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

代码写到35岁

你的鼓励将是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值