Unzip problem with images

S

sham

Hi to all,

I am using ICSharpCode.SharpZipLib.Zip.

My zip file contains a number of images which when they get unzipped only
contain a partial image. The filesize looks correct.

The unziping is done below it is not clear where the problem is. For int
numberOfBytesToRead = (int) zipEntryObject.Size; I initially had the
int numberOfBytesToRead = (int) readStream.length but this always gave me
0.

foreach (ZipEntry zipEntryObject in zipFileObject)
{
System.IO.Stream readStream =
zipFileObject.GetInputStream(zipEntryObject);
int numberOfBytesToRead = (int) zipEntryObject.Size;

byte[] bytes = new byte[numberOfBytesToRead];

readStream.Read(bytes, 0, numberOfBytesToRead);
System.IO.FileStream outputStream =
new System.IO.FileStream(@Directory + zipEntryObject.Name,
System.IO.FileMode.Create);

outputStream.Write(bytes, 0, numberOfBytesToRead);
outputStream.Flush();
outputStream.Close();

}

Sham.
 
M

Marc Gravell

When reading streams, the better approach (and it does it in the ziplib
docs) is to iterate under Read returns <=0; Read is only guaranteed to
return *some* data; I'm guessing this is the problem. You can also save on
the memory footprint by only needing a small buffer, rather than the entire
file size...

The following function (and override) correctly copiesbetween two streams;
use it instead.
Oh, and consider "using" the streams so that they get disposed instead of
finalised - but since you are closing them this will only make a (genuine)
difference when exceptions are thrown.

Marc

/// <summary>
/// Read all data from one stream into another, in user-defined chunks
/// </summary>
/// <param name="input">Stream to read from</param>
/// <param name="output">Target stream</param>
/// <param name="bufferSize">Chunk size (bytes)</param>
/// <returns>The total number of bytes copied</returns>
private long CopyStream(Stream input, Stream output, int bufferSize) {
byte[] buffer = new byte[bufferSize];
int bytesRead;
long totalBytes = 0;
while ((bytesRead = input.Read(buffer, 0, bufferSize)) > 0) {
output.Write(buffer, 0, bytesRead);
totalBytes += bytesRead;
}
output.Flush();
return totalBytes;
}

/// <summary>
/// Read all data from one stream into another
/// </summary>
/// <param name="input">Stream to read from</param>
/// <param name="output">Target stream</param>
/// <returns>The total number of bytes copied</returns>
private long CopyStream(Stream input, Stream output) {
return CopyStream(input, output, 1024);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top