Search code examples
c#sharpcompress

file stream exception on reading zip file (how to use using block)


I'm using the SharpCompress library (that's not the problem). My zips are either unprotected or are password protected (all with the same password). so I'm coding it like this:

using(Stream stream = File.OpenRead(file))
{
    try {
        reader = ZipReader.Open(stream);
        moreFiles = reader.MoveToNextEntry();
    } catch (Exception e) {
        reader = ZipReader.Open(stream, pwd);
        moreFiles = reader.MoveToNextEntry();
    }
    //rest of code
}

It always raises an obscure 'invalid header: xxxxxxxx' exception whenever it gets to the catch block to call MoveToNextEntry because I think the stream is not at the start.

I cannot put a File.OpenRead(file) inside the exception because I'm using a using block. If I use (as suggested in comments) a seek, I get an object reference not set (presumably dispose has been called).

Is there a way to reset this file stream and still ensure it gets disposed (while still using the using block). I didn't know if calling open again would cause the using block to be a bit unhappy also.

Thanks.


Solution

  • Have you tried the following:

    try
    {
        reader = ZipReader.Open(stream);
        moreFiles = reader.MoveToNextEntry();
    }
    catch (CryptographicException e) when (e.Message == "No password supplied for encrypted zip.")
    {
        stream.Seek(0, SeekOrigin.Begin);
        reader = ZipReader.Open(stream, pwd);
        moreFiles = reader.MoveToNextEntry();
    }