c# - 如何使用 C# 从 Azure 容器/Blob 读取/下载所有文件?

标签 c# file azure download azure-cloud-services

我是 Azure 存储的新手。因此,请考虑帖子中的文本/代码。 我在 Azure 存储 上存储了一些文件。

示例:

http://my.blob.core.windows.net/2015/4/10/fea1fc9d-d04102015115229.jpg
http://my.blob.core.windows.net/2015/4/10/asdfc9d-d04102015115229.jpg

现在我想使用 Container/Blob 名称将这些文件下载到特定文件夹。

DownloadFiles.aspx:

protected void Callme(string sourceURLPath)
    {
        string thumbDirectoryName = string.Empty;
        string sourcePath = sourceURLPath;
        string targetUrl = string.Empty;

        CloudStorageAccount cloudStorageAccount;
        CloudBlobClient blobClient;
        CloudBlobContainer blobContainer;
        BlobContainerPermissions containerPermissions;
        CloudBlob blob;
        cloudStorageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=" + ConfigurationManager.AppSettings["AzureStorageAccountName"] + ";AccountKey=" + ConfigurationManager.AppSettings["AzureStorageAccountKey"] + "");
 blobClient = cloudStorageAccount.CreateCloudBlobClient();
  blobContainer = blobClient.GetContainerReference(DateTime.Now.Year.ToString());
  blobContainer.CreateIfNotExist();
 containerPermissions = new BlobContainerPermissions();
  containerPermissions.PublicAccess = BlobContainerPublicAccessType.Blob;
        blobContainer.SetPermissions(containerPermissions);
//need to get files here and download in to specific folder
}

有什么建议吗?

最佳答案

你就快到了:)。以下是您需要执行的操作:

  • 首先,您必须列出容器中的 blob。为此,您可以使用 ListBlobs容器上的方法。列出 Blob 时,请确保将 prefix 作为 空字符串 (string.Empty) 传递,将 useFlatBlobListing 作为 true 传递>。这将给出容器中的 blob 列表。
  • 接下来,您将迭代 Blob 列表,将每个 Blob 转换为 CloudBlockBlob,然后调用 DownloadToFile每个 blob 上的方法。

关于您的代码的一些建议:

  • 由于您正在从 Blob 容器读取文件,因此该容器已经存在。因此无需尝试在每个请求上创建该容器。或者换句话说,从代码中删除这一行:

    blobContainer.CreateIfNotExist();

  • 同样,您也不需要以下代码行,因为您所做的只是读取 blob。

    containerPermissions = new BlobContainerPermissions(); containerPermissions.PublicAccess = BlobContainerPublicAccessType.Blob; blobContainer.SetPermissions(containerPermissions);

关于c# - 如何使用 C# 从 Azure 容器/Blob 读取/下载所有文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30076558/

相关文章:

azure - Azure Functions 上的 Twilio(2.0)

azure - 获取 Azure 中所有服务主体的证书状态,例如证书是否无效,以及最终它们在 Azure 中连接到的内容

azure - 机器人在模拟器中运行完美,但在网络聊天测试中部署时失败发送失败重试错误

c# - 有关远程 IP 地址的信息

c - 在不同的字节范围内读取和写入同一个文件是否线程安全?

java - Android 无法删除文件

java - 将文本文件中的某些 double 值读取到列表中

c# - 字符串上的 ReferenceEquals

c# - 使用foreach将列表/数组中的字符串分配给多个TextBox

c# - 错误 : NU1100: Unable to resolve 'MicrosoftOfficeCore (>= 15.0.0)' for 'net5.0'