C#实现多级子目录Zip压缩解压实例

     

参考

https://blog.csdn.net/lki_suidongdong/article/details/20942977

重点:

实现多级子目录的压缩,类似winrar,可以选择是否排除基准目录

     

     

     

     

     

   

   

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
public bool ZipByRar(string path, string file, string password = "", string exinclude = "")
{
    //  % rar % a - r - EP1 jsusb_arm.zip - x *\jsusb\*.bat jsusb\jsusb\*
    string arguments = "a -r -ep1 -inul ";
    if (!string.IsNullOrEmpty(password))
    {
        arguments += $"-p{password} ";
    }
    if (!string.IsNullOrEmpty(exinclude))
    {
        arguments += $" {exinclude} ";
    }
    arguments += $"\"{file}\" \"{path}\"";
    ProcessStartInfo psi = new ProcessStartInfo(winrarPath, arguments)
    {
        CreateNoWindow = true,
        UseShellExecute = false
    };
 
    using (Process process = Process.Start(psi))
    {
 
        process.WaitForExit();
        if (process.ExitCode != 0)
        {
            return false;
        }
        else
        {
            return File.Exists(file);
        }
    }
 
}
private bool ZipDirectory(string folderToZip, ZipOutputStream zipStream, string parentFolderName, string newRoot = "")
{
    folderToZip = folderToZip.Replace("\\", "/");
    bool result = true;
    string[] folders, files;
    Crc32 crc = new Crc32();
 
    try
    {
        files = Directory.GetFiles(folderToZip);
        foreach (string file in files)
        {
            //使用相对路径
 
            string entPath = file.Substring(parentFolderName.Length + 1).Replace("\\", "/");
            if (!string.IsNullOrEmpty(newRoot))
                entPath = newRoot + "/" + entPath;
            ZipEntry ent = new ZipEntry(entPath);
            using (FileStream fs = File.OpenRead(file))
            {
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
 
                //Console.WriteLine(entPath);
                ent.DateTime = new FileInfo(file).LastWriteTime;
                ent.Size = fs.Length;
                fs.Close();
                crc.Reset();
                crc.Update(buffer);
                ent.Crc = crc.Value;
                zipStream.PutNextEntry(ent);
                zipStream.Write(buffer, 0, buffer.Length);
                zipStream.CloseEntry();
            }
 
            ent = null;
        }
 
    }
    catch (Exception ex)
    {
        result = false;
        throw ex;
    }
 
    folders = Directory.GetDirectories(folderToZip);
    //多级递归时需要记住相对目录
    foreach (string folder in folders)
    {
        if (!ZipDirectory(folder, zipStream, parentFolderName, newRoot))
            return false;
    }
    return result;
}
 
/// <summary>
/// 压缩文件夹 
/// </summary>
/// <param name="folderToZip">要压缩的文件夹路径</param>
/// <param name="zipedFile">压缩文件完整路径</param>
/// <param name="password">密码</param>
/// <param name="newRoot">新的根目录,压缩始终排除根目录,有时为了增加一个新的根目录,可以设置此值。如压缩bin目录,但压缩包里的根目录可以更换为Hello</param>
/// <returns>是否压缩成功</returns>
 
public bool ZipDirectory(string folderToZip, string zipedFile, string password, string newRoot = "")
{
    bool result = false;
    if (!Directory.Exists(folderToZip))
        return result;
 
    ZipOutputStream zipStream = new ZipOutputStream(File.Create(zipedFile));
    zipStream.SetLevel(6);
    if (!string.IsNullOrEmpty(password)) zipStream.Password = password;
 
    //重新设置根目录,默认使用空
    result = ZipDirectory(folderToZip, zipStream, folderToZip, newRoot);
    zipStream.Flush();
    zipStream.Finish();
    zipStream.Close();
    zipStream.Dispose();
    return result;
}
 
调用方法
// string zipResult = ZipByRar(trgPath, zipFileName, "123") ? "成功" : "失败";
string zipResult = ZipDirectory(trgPath, zipFileName, "123",“Hello") ? "成功" : "失败";

  

     

   

posted @   秦秋随  阅读(983)  评论(1编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示