¿Cómo descomprimo un archivo zip en un directorio compartido de archivos de Azure?

programación


Tengo un directorio compartido de archivos de Azure con un archivo zip, digamos abc.zip.
Quiero descomprimir esto con código C# en una función C# de Azure.
Lo que tengo es el CloudFileDirectory lleno correctamente. Ahora quiero llamar a un método que descomprima el archivo que se encuentra en este directorio compartido de archivos de Azure.

El nombre del método es “Tarea asíncrona estática pública ExtractZipFileCloudStorageAsync(CloudFileDirectory extractDirectory)” y toma 1 argumento.

He probado muchos códigos pero nada parece funcionar. El último código que probé es intentar crear una transmisión desde un CloudFile.
La línea de código “usando (var zipArchive = new ZipArchive(stream))” me da un error (catch) => “No se pudo encontrar el final del registro del Directorio Central”.

¿Qué hago mal?

Lo que he probado:

C#
 public static async Task<ResultHelper> ExtractZipFileCloudStorageAsync(CloudFileDirectory extractDirectory)
 {
    try
    {
       var zipFiles = await extractDirectory.ListFilesAndDirectoriesSegmentedAsync(null);

    using (var httpClient = new HttpClient())
    {
        foreach (var zipFile in zipFiles.Results)
        {                        
            if (zipFile is CloudFile file && file.Uri.AbsoluteUri.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
            {                            
                var zipFileBytes = await GetMemoryStreamAsync(file);
                using (var stream = new MemoryStream(zipFileBytes.GetBuffer()))
                {
                    using (var zipArchive = new ZipArchive(stream))
                    {

                    }
                }
            }
        }

         return ...
     }
    catch (Exception ex)
    {
        return ...
    }
}
}

Solución 1

Lo reconstruí y ahora funciona =>

C#
public static class ExtractZipFileHelper
{        
    /// <summary>
    /// Extract zip file for Azure fileshare folders (cloud directory).
    /// </summary>
    /// <param name="extractDirectory"></param>
    /// <returns></returns>
    public static async Task<ResultHelper> ExtractZipFileCloudStorageAsync(CloudFileDirectory extractDirectory)
    {
        try
        {
            if (extractDirectory == null)
            {
                return ResultHelper.CreateResultHelper(false, "The parameter 'extractDirectory' is empty or NULL!");
            }
            
            return await ExtractZipFileAsync(extractDirectory);
        }
        catch (Exception ex)
        {
            return ResultHelper.CreateResultHelper(false, $"Error while extracting zip files: {ex.Message}");
        }
    }        

    /// <summary>
    /// Extract all zip files in the extractDirectory.
    /// </summary>
    /// <param name="extractDirectory"></param>
    /// <returns></returns>
    private static async Task<ResultHelper> ExtractZipFileAsync(CloudFileDirectory extractDirectory)
    {
        try
        {
            var filesAndDirectories = await extractDirectory.ListFilesAndDirectoriesSegmentedAsync(null);
            // Loop through all entries in the CloudFileDirectory.
            foreach (var item in filesAndDirectories.Results)
            {
                // Verify that the item is a CloudFile.
                if (item is CloudFile cloudFile)
                {
                    // Check if the item ends in '.zip'.
                    if (cloudFile.Name.EndsWith(".zip"))
                    {
                        // Create a MemoryStream for the contents of the zip file.
                        using (MemoryStream memoryStream = new MemoryStream())
                        {
                            // Download the contents of the zip file to the MemoryStream.
                            await cloudFile.DownloadToStreamAsync(memoryStream);

                            // Use a ZipArchive to read the contents of the zip file.
                            using (ZipArchive zipArchive = new ZipArchive(memoryStream))
                            {
                                // Walk through all entries in the zip file.
                                foreach (ZipArchiveEntry entry in zipArchive.Entries)
                                {
                                    // Get a reference to the CloudFile object for each entry.
                                    CloudFile entryFile = extractDirectory.GetFileReference(entry.FullName);

                                    // Create a MemoryStream for the entry content.
                                    using (MemoryStream entryStream = new MemoryStream())
                                    {
                                        // Open the entry in the zip file.
                                        using (Stream entryFileStream = entry.Open())
                                        {
                                            // Copy the entry content to the MemoryStream.
                                            await entryFileStream.CopyToAsync(entryStream);
                                        }

                                        entryStream.Position = 0;
                                        // Upload the contents to the corresponding CloudFile.
                                        await entryFile.UploadFromStreamAsync(entryStream);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return ResultHelper.CreateResultHelper(true);
        }
        catch (Exception ex)
        {
            return ResultHelper.CreateResultHelper(false, $"Error while extracting zip files: {ex.Message}");
        }
    }
}

コメント

タイトルとURLをコピーしました