bal*_*569 5 c# unzip sharpziplib
我正在使用SharpZipLib来解压缩文件.我的代码一直很好地适用于所有zip文件,除了我正在提取的zip文件...
得到这个例外:
System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: length
Run Code Online (Sandbox Code Playgroud)
正在抛出异常 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);
}
}
Run Code Online (Sandbox Code Playgroud)
对我来说看起来像个错误.幸运的是,您可以访问代码,因此您应该能够确切地看到它出错的地方.我建议你构建一个SharpZipLib的调试版本,打破抛出异常的行,并查看它实际测试的内容.
即使没有2K的数据,读入2K缓冲区也应该没问题.
(我实际上不会完全按照你的方式编写代码,但这是另一回事.我也将它移动到自己的实用方法中 - 将所有数据从一个流复制到另一个流的行为非常常见.没有需要把它绑在拉链上.)