首页 > 解决方案 > 如何在不下载的情况下读取位于 Azure 容器中的压缩 txt 文件(blob)?

问题描述

我可以使用此代码读取 txt 文件,但是当我尝试读取 txt.gz 文件时,它当然不起作用。我如何在不下载的情况下阅读压缩的 blob,因为该框架将在云上运行?也许可以将文件解压缩到另一个容器?但我找不到解决方案。

public static string GetBlob(string containerName, string fileName)
{
    string connectionString = $"yourConnectionString";

    // Setup the connection to the storage account
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

    // Connect to the blob storage
    CloudBlobClient serviceClient = storageAccount.CreateCloudBlobClient();
    // Connect to the blob container
    CloudBlobContainer container = serviceClient.GetContainerReference($"{containerName}");
    // Connect to the blob file
    CloudBlockBlob blob = container.GetBlockBlobReference($"{fileName}");
    // Get the blob file as text
    string contents = blob.DownloadTextAsync().Result;

    return contents;
}

标签: c#azureazure-blob-storageunzip

解决方案


您可以使用 GZipStream 即时解压缩您的 gz 文件,您不必担心下载它并在物理位置解压缩它。

public static string GetBlob(string containerName, string fileName)
{
    string connectionString = $"connectionstring";

    // Setup the connection to the storage account
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

    // Connect to the blob storage
    CloudBlobClient serviceClient = storageAccount.CreateCloudBlobClient();
    // Connect to the blob container
    CloudBlobContainer container = serviceClient.GetContainerReference($"{containerName}");
    // Connect to the blob file
    CloudBlockBlob blob = container.GetBlockBlobReference($"{fileName}");
    // Get the blob file as text
    using (var gzStream = await blob.OpenReadAsync())
    {
        using (GZipStream decompressionStream = new GZipStream(gzStream, CompressionMode.Decompress))
        {
            using (StreamReader reader = new StreamReader(decompressionStream, Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }
    }
}

推荐阅读