Getting FileNotFoundException when saving to a memory stream and then to a file

Oct 20, 2010 at 9:02 AM
Edited Oct 20, 2010 at 9:05 AM

Everything is in the tittle, I think ;)

Basically, when I use this code, I'm getting FileNotFoundException error at the last line.


MemoryStream compressedStream = new MemoryStream();

ZipFile zipFile = new ZipFile(); zipFile.AddFile( "myFile.txt" ); zipFile.Save( compressedStream );
// error doesn't exist
zipFile.Save( "" );

Maybe this problem is specified somewhere in the docs, but I didn't find it...


Oct 20, 2010 at 8:12 PM

Hi Mmanatane,

I've reproduced the problem here.

Digging around in the code it looks like the first call to ZipFile.Save makes some changes to the internal state of the ZipFile object, and when you call Save again it tries to use this internal state to optimise the second save by avoiding recompressing files where it can. In this case it tries to read the pre-compressed bytes for each entry from a existing zip file, but the optimisation fails if the first Save was to a stream because it's trying to read from a file which doesn't exist at that point.

In your case some options to work around this are:

+ Move back to the start of your compressedStream and simply write the bytes out to the disk file yourself.

+ Perform 2 rounds of compression - one to memory and one to disk - with a new ZipFile object each time.

I'm sure Cheeso will have more insight into this, but the above will hopefully help in the meantime.



P.S, for the record, the following fails as well:

ZipFile zipFile = new ZipFile();

zipFile.AddFile( "myFile.txt" );
zipFile.Save( compressedStream );
// error - "Object reference not set to an instance of an object."
zipFile.Save( compressedStream );