5

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

得到这个例外:

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

异常被抛出 size = s.Read(data, 0, data.Length);

Hereb是我的代码...

 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);
        }
    }
4

3 回答 3

5

对我来说似乎是一个错误。幸运的是,您可以访问代码,因此您应该能够准确地看到哪里出错了。我建议你构建一个 SharpZipLib 的调试版本,在抛出异常的那一行打断,看看它实际在测试什么。

即使没有剩下 2K 的数据,读入 2K 缓冲区也应该没问题。

(我实际上不会按照您的方式编写代码,但那是另一回事。我也会将它移到它自己的实用程序方法中 - 将所有数据从一个流复制到另一个流的行为很常见。没有需要将其系在拉链上。)

于 2010-12-14T07:10:25.347 回答
-1

查看代码,您正在再次读取同一组字节(并推进位置)。

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

此处的示例显示第二个参数应该是移动位置而不是固定数字。

于 2010-12-14T07:06:18.743 回答
-1

将您的代码更改 int size = 2048;int size = data.Length;. 您不会接受 OutOfRange 异常。

 using (FileStream streamWriter = File.Create(targetDirectory + fileName))
    {
       int size = data.Length;
       byte[] data = new byte[size];
       while (true)
       {
            size = s.Read(data, 0, data.Length);
            if (size > 0)
            {
                streamWriter.Write(data, 0, size);
            }
            else
            {
               break;
            }
       }
    }
于 2010-12-14T07:15:53.990 回答