【问题标题】:How to read Zipped txt file (blob) which locates in Azure container without downloading?如何在不下载的情况下读取位于 Azure 容器中的压缩文本文件(blob)?
【发布时间】:2021-04-21 06:08:38
【问题描述】:

我可以使用此代码读取 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;
}

【问题讨论】:

  • 你知道gz和zipping不一样吗?
  • 哦,是的,谢谢,但是gz也有问题,我需要.txt文件。

标签: c# azure azure-blob-storage unzip


【解决方案1】:

无需下载,因为框架可以在云端运行

这是不可能的。如果不下载,您将无法使用 Blob 存储上的文件。无论您的代码在哪里运行。当然,如果您的代码也在 Azure 上运行,下载时间可能会非常快,但您必须先从 blob 存储下载。

对于您的 zip 文件,您希望使用 DownloadToFileAsync() 或 DownloadToStreamAsync()。

【讨论】:

    【解决方案2】:

    您可以使用 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();
                }
            }
        }
    }
    

    【讨论】:

    • Sadiqs 的答案很准确。我认为你明天需要阅读一些 C# 基础知识
    • 它有效,谢谢:) 另一个问题>> 它可以从测试容器中读取,它如何读取子文件夹?我尝试将 test\\testFolder1\\testFolder2 作为容器名称,但得到 BlobNotFound 异常。
    • 容器名称为“test”,文件名为“testFolder/testFolder2/test.txt.gz”
    • 谢谢 Sadiq Khoja。它有效,我很感激
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 2020-09-08
    • 2023-03-21
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    相关资源
    最近更新 更多