Bagaimana cara mengekstrak file zip di direktori fileshare Azure

pemrograman


Saya memiliki direktori berbagi file Azure dengan file zip, katakanlah abc.zip.
Saya ingin mengekstrak ini dengan kode C# dalam fungsi C# Azure.
Yang saya miliki adalah CloudFileDirectory yang terisi dengan benar. Sekarang saya ingin memanggil metode untuk mengekstrak file yang ada di direktori berbagi file Azure ini.

Nama metodenya adalah “Tugas async publik statis ExtractZipFileCloudStorageAsync(CloudFileDirectory extractDirectory)” dan membutuhkan 1 argumen.

Saya telah mencoba banyak kode tetapi sepertinya tidak ada yang berhasil. Kode terakhir yang saya coba adalah mencoba membuat streaming dari CloudFile.
Baris kode “menggunakan (var zipArchive = new ZipArchive(stream))” memberi saya kesalahan (catch) => “End of Central Directory record tidak dapat ditemukan.”

Apa yang saya lakukan salah?

Apa yang saya coba:

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 ...
    }
}
}

Solusi 1

Saya membangunnya kembali dan sekarang berfungsi =>

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をコピーしました