/*************************************
* 功 能:文件处理工具类.
* 创 建 人: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);
}
}
}
}
}
}
}
}
}
08-04
1763
04-26
1402
06-03