'I keep getting the error `Central Directory corrupt` when trying to use ZipArchive

My code looks like below.

public async Task<MetaDataItem> GetMetadata(Stream sm){
    using (ZipArchive archive = new ZipArchive(sm, ZipArchiveMode.Read, true))
    {
        if (archive.Entries.Count == 0)
        {
            return null;
        }
        foreach (ZipArchiveEntry entry in archive.Entries)
        {
            MetaDataItem metaItem = new MetaDataItem();
            //process contents of archive
            return metaItem;
        }

    }
    return null;

}

public async Task<bool> ExtractData(Stream sm, string file){
    string ext = Path.GetExtension(file);
    if (ext.ToLower().Equals(".zip"))
    {
        isZip = true;
        using (var archive = new ZipArchive(sm, ZipArchiveMode.Read, true))
        {
            // Some processing on the entries here.
            return true;
        }
    }
    return false;

}

var objectStream  = await cloudDataManager.DownloadPackage(dataKey);

using(objectStream){
    var metadata = await GetMetadata(objectStream); 
    var res = await ExtractData(objectStream, dataKey);
}

At the line using (var archive = new ZipArchive(sm, ZipArchiveMode.Read, true)) in ExtractData I get the exception:

Central Directory corrupt.
[System.IO.IOException] = {"An attempt was made to move the position before the beginning of the stream."}

Note sure what is wrong here or how to fix it.

For some context, cloudDataManager.DownloadPackage(dataKey) downloads a zip file from could storage (S3) bucket. I can confirm that this function does not close (dispose) the stream that is returned.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source