title: Zip and Unzip within Memorystream
body: <p>I'm trying to save some files in a String. </p>
  
  <p>The files are zipped, the zip-file read as ByteArray, and the ByteArray is converted into a String using <code>Convert.ToBase64String</code>.</p>
  
  <p>When I used to Create an actual Zip-File it worked, but now I'm trying to do it in MemoryStream and I get:</p>
  
  <blockquote>
    <p>FileFormatException: "File contains corrupted data."</p>
  </blockquote>
  
  <p>Here's a Function I've been using to diagnose the problem:</p>
  
  <pre><code>Private Sub PushToBase64StringStream(tSourceDirPath As String)
      Dim byteArray() As Byte
  
      Using cStream As New MemoryStream
          ZipManagedFilesStream(cStream, tSourceDirPath)
  
          cStream.Seek(0, SeekOrigin.Begin)
          byteArray = New Byte(CType(cStream.Length, Integer)) {}
          cStream.Read(byteArray, 0, CInt(cStream.Length))
          'Base64String = Convert.ToBase64String(byteArray)
  
          ' This statement works
          Using cPackage As Package = Package.Open(cStream, FileMode.Open, FileAccess.Read)
      End Using
  
      Using cStream2 As New MemoryStream
          cStream2.Write(byteArray, 0, byteArray.Length)
          cStream2.Seek(0, SeekOrigin.Begin)
  
          ' This statement fails
          Using cPackage As Package = Package.Open(cStream2, FileMode.Open, FileAccess.Read)
          End Using
      End Using
  
  End Sub
  </code></pre>
  
  <p>In the first Using-Statement I call the Unzip-Function using the original stream and it works. In the second Using-Statement I call the Unzip-Function using a new Stream which is filled with the original byteArray and it fails, claiming the File is corrupted. </p>
  
  <pre><code>Private Sub ZipManagedFilesStream(cStream As Stream, tSourceDirectory As String)
      Using cPackage As Package = Package.Open(cStream, FileMode.Create)
          For Each cFile As FileInfo In ManagedFiles(tSourceDirectory)
  
              Dim tType As String = Net.Mime.MediaTypeNames.Application.Zip
              Dim cPartUri As New Uri("/" &amp; cFile.Name, UriKind.Relative)
              Dim cPackagePart As PackagePart = cPackage.CreatePart(cPartUri, tType, CompressionOption.Normal)
  
              Using cSourceStream As New FileStream(cFile.FullName, FileMode.Open, FileAccess.Read),
                    cTargetStream As Stream = cPackagePart.GetStream
                  cSourceStream.CopyTo(cTargetStream)
              End Using
          Next
      End Using
  End Sub
  </code></pre>