Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...