c# - DotNetZip - Cannot access a closed Stream -


none of similar questions quite i'm looking for!

what's wrong following code? files text array of file contents, , filenames corresponding filename array.

this code fails @ second-last line save method, can't see why stream closed!

result = new memorystream();  using (zipfile zipfile = new zipfile()) {     (int = 0; < files.count(); i++)     {         system.text.asciiencoding encoding = new system.text.asciiencoding();         byte[] bytes = encoding.getbytes(files[i]);         using (memorystream fs = new memorystream(bytes))         {             zipfile.addentry(filenames[i], fs);         }     }     zipfile.save(result); } 

thanks - getting desperate here!

this solution based on @spender's first comment, although solution posted below possibly nicer.

        try         {             result = new memorystream();             list<stream> streams = new list<stream>();              if (files.count > 0)             {                 using (zipfile zipfile = new zipfile())                 {                     (int = 0; < files.count(); i++)                     {                          system.text.asciiencoding encoding = new system.text.asciiencoding();                         byte[] bytes = encoding.getbytes(files[i]);                         streams.add(new memorystream(bytes));                         zipfile.addentry(filenames[i], streams[i]);                     }                     zipfile.save(result);                 }             }         }         catch (exception ex)         {             throw;         } 

it seems calling save point when source streams read. means have keep them undisposed until after save. abandon using statement in case impossible extend scope beyond loop. instead, collect idisposables , dispose of them once save completed.

result = new memorystream();  using (zipfile zipfile = new zipfile()) {     list<idisposable> memstreams = new list<idisposable>();     try     {         (int = 0; < files.count(); i++)         {             system.text.asciiencoding encoding = new system.text.asciiencoding();             byte[] bytes = encoding.getbytes(files[i]);             memorystream fs = new memorystream(bytes);             zipfile.addentry(filenames[i], fs);             memstreams.add(fs);         }         zipfile.save(result);     }         {         foreach(var x in memstreams)         {             x.dispose();         }     } } 

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -