C# 调用7z压缩Win32Exception异常

原因

在使用 C# 调用了7z外部工具对文件进行压缩时,当太多文件打成一个7z包的话,会报 Win32Exception 错误。使用 Process.Start 来调用外部 7z 应用程序,当参数少的没有进行报错。参考文档, https://msdn.microsoft.com/en-us/library/h6ak8zt5%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 发现有对参数的长度进行限制,如下所示:

The sum of the length of the arguments and the length of the full path to the process exceeds 2080. The error message associated with this exception can be one of the following: "The data area passed to a system call is too small." or "Access is denied."

解决

那么寻找其他方法,参考7z的命令行说明 https://sevenzip.osdn.jp/chm/cmdline/syntax.htm 可以看到有提供文件列表方式:


可以通过先将要压缩的文件名保存到文本文件,然后再进行调用压缩,处理类似如下所示:
public static string CompressFilesTo7zSafe(string workdir, List files, string outputPath)
{
    const string tmpFileName = "7zListFileTmp.txt";
    string compressExe = Get7zExePath();
    string listFileTmp = Path.Combine(workdir, tmpFileName);

    FileUtils.DeleteFile(listFileTmp);
    File.WriteAllLines(listFileTmp, files.ToArray());

    var exeArgs = "a -t7z " + outputPath + " @" + tmpFileName;
    var outputStr = RunExe(compressExe, exeArgs, workdir);

    if (string.IsNullOrEmpty(outputStr) || outputStr.IndexOf("Everything is Ok", StringComparison.Ordinal) == -1)
    {
        outputStr = "压缩文件失败\n" + outputStr;
    }
    else
    {
        outputStr = string.Empty;
    }
    FileUtils.DeleteFile(listFileTmp);
    return outputStr;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值