Read file from Azure blob storage

2019-03-15 11:11发布

问题:

I want to read a PDF file bytes from azure storage, for that I have a file path.

https://hostedPath/pdf/1001_12_Jun_2012_18_39_05_594.pdf

So it possible to read content from blob storage by directly passing its Path name? Also I am using c#.

回答1:

As long as the blob is public, you can absolutely pass the blob url. For instance, you can embed it in an html image or link:

<a href="https://myaccount.blob.core.windows.net/pdf/1001_12_Jun_2012_18_39_05_594.pdf">click here</a>

By default, blob containers are private. To enable public read access, you just have to change the container permissions when creating the container. For instance:

var blobStorageClient = storageAccount.CreateCloudBlobClient();
var container = blobStorageClient.GetContainerReference("pdf");
container.CreateIfNotExist();

var permissions = container.GetPermissions();
permissions.PublicAccess = BlobContainerPublicAccessType.Container;
container.SetPermissions(permissions);


回答2:

Just like David explained you can access any blob through its url as long as the container is not private.

If the container is private you can still make your files accessible through the url by using Shared Access Signatures (SAS). This will allow you grant users the right do download the file (by providing them with the SAS, usually appended to the URL) but limiting them in time.

This is perfect when you have paying downloads for example, to protect your files but allowing them to be downloaded for a limited time if someone payed for it.

Now, in your question you state that you're using C#. If you want to download the file in a WPF/Windows Forms/Console application, you can simply use the WebClient to download the file (if the container is public or you append the URL with the SAS):

WebClient myWebClient = new WebClient();
myWebClient.DownloadFile("https://myaccount.blob.core.windows.net/pdf/1001_12_Jun_2012_18_39_05_594.pdf", @"D:\Data\myPdfFile.pdf");