C#使用Squid-Box.SevenZipSharp压缩文件时出现Execution has failed错误如何解决?
使用 Squid-Box.SevenZipSharp 实现压缩功能报错排查
问题场景
近期项目引入 NuGet 包 Squid-Box.SevenZipSharp 实现文件压缩、解压能力,实际测试压缩流程时始终执行失败,初步判断问题大概率来自底层依赖的7z原生dll库。
测试阶段已完成的排查动作:
- 分别准备32位、64位版本的7z原生dll,严格匹配项目编译架构(32位dll对应x86编译配置、64位dll对应x64编译配置)分别测试
- 手动将对应dll复制到系统临时目录,通过
SetLibraryPath方法显式指定dll加载路径 - 两种架构配置下抛出的异常完全一致,暂未定位到问题根因
实际测试代码
private void Compress(string source, string output) { /*32-bits version*/ string path = Directory.GetCurrentDirectory() + @"\32-7z.dll"; //64-bits version string path = Directory.GetCurrentDirectory() + @"\64-7z.dll"; SevenZipCompressor compressor = new SevenZipCompressor(); compressor.ArchiveFormat = OutArchiveFormat.Zip; compressor.TempFolderPath = Path.GetTempPath(); compressor.CompressionMode = SevenZip.CompressionMode.Create; compressor.CompressionLevel = SevenZip.CompressionLevel.Fast; compressor.CompressionMethod = CompressionMethod.Lzma2; compressor.ZipEncryptionMethod = ZipEncryptionMethod.Aes256; var assemblyDllPath = compressor.TempFolderPath + "32-7z.dll"; //var assemblyDllPath = compressor.TempFolderPath + "64-7z.dll"; File.Copy(path, assemblyDllPath, overwrite: true); SevenZipExtractor.SetLibraryPath(path); compressor.CompressDirectory(@"A:\C#\random", @"A:\C#\empty\archive.zip", "password"); }
运行时抛出的异常详情
SevenZip.SevenZipException HResult=0x80131500 Message = Execution has failed due to an internal SevenZip issue (0x80004001 / -2147467263). Please report it to the project repository, include the release number, 7z version used, and attach the archive. Source = SevenZipSharp
触发该异常的常见原因与修复方向
- 原生dll版本不匹配:Squid-Box分支的SevenZipSharp对底层7z原生dll的版本有严格适配要求,任意从官网下载的通用7z.dll无法和库内部的接口调用逻辑匹配,会直接抛出未实现接口的0x80004001异常,需要使用和当前NuGet包版本完全配套的原生dll
- 压缩参数兼容性问题:代码指定
ArchiveFormat.Zip输出格式时使用了Lzma2压缩算法,标准Zip格式对Lzma2的支持需要底层库做特殊适配,可临时替换为Deflate算法测试,验证是否为参数不兼容导致的执行失败 - 原生dll加载顺序错误:当前代码流程是先实例化
SevenZipCompressor对象,之后才调用SetLibraryPath指定dll路径,库内部在Compressor对象初始化时就会加载默认路径下的7z.dll,后续修改路径的操作不会生效。需要将SetLibraryPath调用放到所有SevenZip相关类实例化的最前面,确保库加载到正确的原生dll - 目录权限不足:代码涉及的临时目录、源文件目录、压缩包输出目录需要提前校验进程的读写权限,无写入权限时会导致dll复制、压缩包写入失败,触发内部执行异常
内容的提问来源于stack exchange,提问作者Cicker
相关产品推荐
相关产品推荐

