Miguel Moura
Miguel Moura

Reputation: 39524

Convert Stream from file in archive to Byte[]

On Net Core 2.1 I am trying to read files from a ZIP archive.

I need to convert each file content into a Byte[] so I have:

using (ZipArchive archive = ZipFile.OpenRead("Archive.zip")) {

  foreach (ZipArchiveEntry entry in archive.Entries) {

    using (Stream stream = entry.Open()) {

      Byte[] file = new Byte[stream.Length];

      stream.Read(file, 0, (Int32)stream.Length);

    }

  }

}

When I run it I get the error:

Exception has occurred: CLR/System.NotSupportedException
An exception of type 'System.NotSupportedException' occurred in System.IO.Compression.dll but was not handled in user code: 
'This operation is not supported.' at System.IO.Compression.DeflateStream.get_Length()

How can I get the content into a Byte[] for each file?

Upvotes: 3

Views: 1520

Answers (1)

Tequila
Tequila

Reputation: 736

Try to do something like this:

using (ZipArchive archive = ZipFile.OpenRead("archieve.zip")) 
{

   foreach (ZipArchiveEntry entry in archive.Entries) 
   {
      using (Stream stream = entry.Open()) 
      {
         byte[] bytes;
         using (var ms = new MemoryStream()) 
         {
            stream.CopyTo(ms);
            bytes = ms.ToArray();
         }
      }
   }
}

Upvotes: 6

Related Questions