Reputation: 11010
I'm using SharpZipLib to unzip files. My code has been working nicely for all zipfiles except the zip file what i am extracting now...
Got this exception:
System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: length
The exception is being thrown at size = s.Read(data, 0, data.Length);
Hereb is my code...
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);
}
}
Upvotes: 5
Views: 2088
Reputation: 764
Change your code int size = 2048;
to int size = data.Length;
. You won't take OutOfRange exception.
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;
}
}
}
Upvotes: -1
Reputation: 1500375
Looks like a bug to me. Fortunately, you have access to the code, so you should be able to see exactly where it's going wrong. I suggest you build a debug version of SharpZipLib, break on the line which is throwing the exception, and have a look at what it's actually testing.
It should be fine to read into a 2K buffer even if there's not 2K of data left.
(I wouldn't actually write the code quite how you have, but that's a different matter. I'd also move it into its own utility method - the act of copying all the data from one stream to another is pretty common. There's no need to tie it to zip.)
Upvotes: 5
Reputation: 33476
Looking at the code, you are reading the same set of bytes again (and advancing the position).
size = s.Read(data, 0, data.Length);
An example from here shows that the 2nd argument should be a moving position & not a fixed number.
Upvotes: -1