0

I have a zip file(.Exe - Self-extracting zip file) that can be extracted using 7zip. As I want to automate the extraction process, I used the below C# code. It is working for the normal 7z files. But facing this issue 'Cannot access the closed Stream', when I trying to extract the specific self-extracting (.Exe) zip file. Fyi. Manually I ensured the 7zip command line version is unzipping the file.

using (SevenZipExtractor extract = new SevenZipExtractor(zipFileMemoryStream))
    {
        foreach (ArchiveFileInfo archiveFileInfo in extract.ArchiveFileData)
        {
            if (!archiveFileInfo.IsDirectory)
            {
                using (var memory = new MemoryStream())
                {
                    string shortFileName = Path.GetFileName(archiveFileInfo.FileName);
                    extract.ExtractFile(archiveFileInfo.Index, memory);
                    byte[] content = memory.ToArray();
                    file = new MemoryStream(content);
                }
            }
        }
    }

The zip file is in Azure blob storage. I dont know how to get the extracted files in the blob storage.

Kathir Subramaniam
  • 1,195
  • 1
  • 13
  • 27
  • Did you check your code would be able to unzip the file locally ? And knowing where the error is thrown would help, because from what you're telling us, the problem seems to be that you are trying to access an already closed stream. – Irwene Jan 24 '22 at 15:49
  • Have you downloaded the entire file from Azure - and have it in memory - before this code is executed? Assuming you're dealing with an in-memory `MemoryStream` there should not be any issue with the fact that it came off Azure. I suspect the issue is occurring earlier than the code you posted, i.e., the contents of `zipFileMemoryStream` are incomplete. Also did you remember to reset the `Position` of that stream to `0`? That one gets me a lot... – Emperor Eto Jan 24 '22 at 19:14

1 Answers1

1

Here is one of the workarounds that has worked for me. Instead of 7Zip I have used ZipArchive.

ZipArchive archive = new ZipArchive(myBlob);
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(destinationStorage);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(destinationContainer);

foreach(ZipArchiveEntry entry in archive.Entries) {
  log.LogInformation($"Now processing {entry.FullName}");

  string valideName = Regex.Replace(entry.Name, @ "[^a-zA-Z0-9\-]", "-").ToLower();

  CloudBlockBlob blockBlob = container.GetBlockBlobReference(valideName);
  using(var fileStream = entry.Open()) {
    await blockBlob.UploadFromStreamAsync(fileStream);
  }
}

REFERENCE: How to Unzip Automatically your Files with Azure Function v2

SwethaKandikonda
  • 7,513
  • 2
  • 4
  • 18