C#通过命令行调用7-Zip实现文件压缩与解压

远山来客
远山来客
发布时间:2026-10-16| 6人浏览过
原创

C#中常需处理文件归档。本文将通过System.Diagnostics.Process类调用命令行工具7-Zip,演示如何以编程方式压缩单个文件或目录为zip格式,以及如何从zip包中提取文件到指定目录。该方法适用于Windows环境下的自动化部署或批量处理任务。

准备条件

在执行代码前,请确保满足以下条件:

  • 安装7-Zip:已安装7-Zip且默认路径包含 c:\progra~1\7-zip\(即Program Files的短文件名映射)。若安装在其他位置,需相应修改代码中的路径。
  • 引用命名空间:确保代码文件中已引入 using System.Diagnostics;。

第1步:实现文件压缩功能

本步骤目的是将源文件(或文件夹)打包成ZIP格式。通过向cmd发送多行命令,切换至7-Zip目录并执行a(add)指令。

1. 设置压缩入口函数

定义一个接收源文件路径和目的文件路径的方法,并添加对.zip后缀的自动补全逻辑。

public object CompressZipFile(string sourceFile, string destinationFile)
{
    object resObj;
    Process process = new Process();
    try
    {
        // 如果未指定.zip后缀,自动追加
        string targetDest = destinationFile.ToLower().EndsWith(".zip") 
            ? destinationFile 
            : destinationFile + ".zip";

        process.StartInfo.FileName = "cmd.exe";
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardInput = true;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardError = true;
        process.StartInfo.CreateNoWindow = true;
        process.Start();

        // 构建命令序列:切换到C盘根目录 -> 进入7-Zip短路径目录 -> 执行压缩
        string cmdDir = @"cd c:\progra~1\7-zip";
        process.StandardInput.WriteLine(@"c:");
        process.StandardInput.WriteLine(@"cd\");
        process.StandardInput.WriteLine(cmdDir);
        process.StandardInput.WriteLine(@"7Z a -tzip " + targetDest + " " + sourceFile);
        process.StandardInput.WriteLine("exit");

        string output = process.StandardOutput.ReadToEnd();
        // 检查成功标志
        if (output.ToUpper().IndexOf("EVERYTHING IS OK") > -1)
        {
            resObj = new object[] { 0, "Compress file[" + targetDest + "] OK" };
        }
        else
        {
            resObj = new object[] { 1, "Compress File[" + targetDest + "] Error!" };
        }
    }
    catch (Exception ex)
    {
        resObj = new object[] { 1, "Compress File exception:" + ex.Message };
    }
    return resObj;
}

第2步:实现文件解压功能

本步骤目的是将ZIP包中的内容提取到指定目录。利用cmd的/c参数直接传递完整命令比逐行写入stdin更为简洁。

1. 设置解压入口函数

构建包含解压参数 -o(输出目录)和 -y(确认全部操作)的命令字符串。

public object DecompressFile(string zipFilepath, string fileDir)
{
    object resObj;
    try
    {
        // 构建解压命令:7z.exe x 源文件 -o目标目录 -y
        string command = @"c:\progra~1\7-zip\7z.exe x " + zipFilepath + " -o" + fileDir + " -y";

        Process process = new Process();
        process.StartInfo.FileName = "cmd.exe";
        process.StartInfo.Arguments = "/c " + command;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardInput = true;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardError = true;
        process.StartInfo.CreateNoWindow = true;
        process.Start();

        string output = process.StandardOutput.ReadToEnd();
        // 检查结果日志
        if (output.ToUpper().IndexOf("EVERYTHING IS OK") > -1)
        {
            resObj = new object[] { 0, "解压完成" };
        }
        else
        {
            resObj = new object[] { 1, "解压出错!" };
        }
    }
    catch (Exception ex)
    {
        resObj = new object[] { 1, ex.Message };
    }
    return resObj;
}

完成判断

上述两个方法均返回object数组,结构为 {返回值状态码, 描述信息}。状态码 0 表示成功,>0 表示失败或异常。程序通过检索输出流中的 EVERYTHING IS OK 字符串来判定压缩或解压是否顺利执行完毕。若捕获到 Exception,则视为运行时错误。

简要总结

使用C#调用外部命令行工具是实现系统级文件操作的有效手段。通过正确配置 ProcessStartInfo 的重定向属性,开发者可以实时获取7-Zip的执行结果。注意根据实际环境调整7-Zip的安装路径,以确保命令能够被系统找到。

以上就是C#通过cmd调用7z软件实现压缩和解压文件的详细内容,更多关于C# 7-Zip编程的资料请关注本站其它相关文章!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。