0

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.

CarenRose
  • 1,266
  • 1
  • 12
  • 24
Neil Walker
  • 6,400
  • 14
  • 57
  • 86

1 Answers1

1

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();
}
  • I get an exception of object reference not set. Presumably the dispose has been called then? – Neil Walker Apr 09 '16 at 20:45
  • 1
    I've just tried it with SharpCompress 0.11.5 and it worked. I'm updating the answer with the full code I've tried. I've also edited the catch statement to just handle the exception for password protection. If you're not in C# 6.0 you can omit the when directive. –  Apr 09 '16 at 21:02
  • Thanks :) I guess I missed out the open afterwards. – Neil Walker Apr 09 '16 at 21:22