c# - 如何在不下载的情况下读取位于 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;
}
解决方案
您可以使用 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();
}
}
}
}
推荐阅读
- jquery - Laravel 导航栏切换在 bootstrap 4.4.1 和 jquery 3.3 上不起作用
- python - Discord.py 命令引发异常:AttributeError: 'dict' object has no attribute 'json'
- javascript - 已解决:错误:元素类型无效...得到:未定义。检查“发现”的渲染方法
- javascript - webpack 包不让 html 识别我的 js 函数
- cassandra - 在未提供聚类列的情况下,每个分区由一行组成
- c# - 提取部分 JSON 内容(属性)并转换为 c# 对象?
- node.js - Node js路由顺序搞砸了
- wordpress - Wordpress Elementor 标题问题
- python - Python有序链表与引用正确名称的混淆
- android-studio - 在 VScode 和 Android Studio 中使用 Gradle 进行颤振时出错