简体   繁体   中英

How to read Zipped txt file (blob) which locates in Azure container without downloading?

I can read txt file with this code, but when I try to read the txt.gz file of course it doesn't work. How can I read zipped blob without downloading, because the framework will work on cloud? Maybe it is possible to unzip the file to another container? But I couldn't find a solution.

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

You can use GZipStream to decompress your gz file on the fly, you don't have to worry about downloading it and decompressing it on a physical location.

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();
            }
        }
    }
}

without downloading, because the framework will work on cloud

This is not possible. You cannot work with a file on blob storage without downloading it. No matter where your code is running. Of course, if your code is also running on Azure, the download time might be pretty fast, but nevertheless you have to download from blob storage first.

And for your zip file you want to use either DownloadToFileAsync () or DownloadToStreamAsync ().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM