c# - SharpZipLib - ZipException "System.ArgumentOutOfRangeException"- 为什么我会收到此异常?

标签 c# unzip sharpziplib

我正在使用 SharpZipLib 解压缩文件。除了我现在提取的 zip 文件之外,我的代码对所有 zip 文件都运行良好...

得到这个异常:

System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: length

异常在 size = s.Read(data, 0, data.Length);

处被抛出

这是我的代码...

 public static void UnzipFile(string sourcePath, string targetDirectory)
     {
        try
        {
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(sourcePath)))
            {
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    //string directoryName = Path.GetDirectoryName(theEntry.Name);
                    string fileName = Path.GetFileName(theEntry.Name);

                    if (targetDirectory.Length > 0)
                    {
                        Directory.CreateDirectory(targetDirectory);
                    }

                    if (fileName != String.Empty)
                    {
                        using (FileStream streamWriter = File.Create(targetDirectory + fileName))
                        {
                            int size = 2048;
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception("Error unzipping file \"" + sourcePath + "\"", ex);
        }
    }

最佳答案

在我看来像是一个错误。幸运的是,您可以访问代码,因此您应该能够准确地看到哪里出错了。我建议您构建 SharpZipLib 的调试版本,在抛出异常的行上打断,并查看它实际测试的内容。

即使没有 2K 数据剩余,也应该可以读入 2K 缓冲区。

(我实际上不会完全按照您的方式编写代码,但那是另一回事。我还将其移至其自己的实用方法中 - 将所有数据从一个流复制到另一个流的行为非常常见. 没有必要把它绑在 zipper 上。)

关于c# - SharpZipLib - ZipException "System.ArgumentOutOfRangeException"- 为什么我会收到此异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4436658/

相关文章:

c# - 在内存中提取tgz文件并在C#中访问文件

c# - 如何在 C# 中解压 .bz2 文件?

c# - 更改 Windows 窗体应用程序中的字体大小

c# - 将多个复杂对象传递给 post/put Web API 方法

c# - AND 运算不能应用于可为空的 bool 值之间

java - 提取 zip 存档而不丢失文件夹

github - GitHub设置master.zip的文件夹结构

C# 网络流压缩 - Sharpziplib、DotNetZip、gzipstream 在我的流上均出现错误

c# - ASP.NET Core Entity Framework Core 找不到 IndexAttribute

iphone - 如何显示文件解压进度?