原因
在使用 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;
}