首页 > 解决方案 > 如何从 C# Core 中的 azure blob 存储中读取所有文件

问题描述

我想从 azure blob 存储(文件夹内的文件)中读取文件,blob 存储包含许多文件夹。我想读取我的文件夹“blobstorage”,它包含许多 JSON 文件,对每个文件执行 .read 和一些操作。我尝试了许多不起作用的代码:

 CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container = blobClient.GetContainerReference($"blobstorage");

上面的代码使用 'Microsoft.WindowsAzure.Storage' nuget 包。此代码未按预期工作。在堆栈溢出中发现的许多问题和答案中,我发现它们中的大多数已经过时并且不起作用。注意:如果有任何 nuget 提到 bcs 他们是很多包

标签: c#azure.net-coreazure-storageazure-blob-storage

解决方案


我在这篇文章中找到了解决方案,并为我完美地工作。您只需在下载后将其作为普通流读取即可。

BlobServiceClient blobServiceClient = new BlobServiceClient("connectionString");
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient("containerName");
BlobClient blobClient = containerClient.GetBlobClient("blobName.csv");
if (await blobClient.ExistsAsync())
{
  var response = await blobClient.DownloadAsync();
  using (var streamReader= new StreamReader(response.Value.Content))
  {
    while (!streamReader.EndOfStream)
    {
      var line = await streamReader.ReadLineAsync();
      Console.WriteLine(line);
    }
  }
}

推荐阅读