Using this to create and read a zip in memory

Jul 10, 2011 at 11:42 PM

Below I'm attempting to create a zip file, and then read it. However it's throwing an InvalidDataException.

            var someFileToStore = new MemoryStream(Encoding.UTF8.GetBytes("Hello World!")); ;
            var zipStream = new MemoryStream();
            ZipStorer zip = ZipStorer.Create(zipStream, "test");
            zip.AddStream(ZipStorer.Compression.Store, "/Hello.txt", someFileToStore, DateTime.Now.AddDays(-1), "Test");
            byte[] bytes = zipStream.ToArray();
            zip.Close();

            var fileAsStream = new MemoryStream(bytes);

            // Throws exception here...
            ZipStorer.Open(fileAsStream, FileAccess.Read);

Any thoughts?

Oct 31, 2011 at 9:38 AM

You need to call the close method before calling ToArray

byte[] bytes = zipStream.ToArray();
zip.Close();

should be

zip.Close();
byte
[] bytes = zipStream.ToArray();
Coordinator
Nov 3, 2011 at 5:47 PM

Thanks CodeSmoke,

That's the right answer.

Jaime.