All examples below assume that we have already instantiated CloudBlobClient cloudBlobClient. It can be done using the code.
Upload a Blob from a string
First example, upload a string as a text file. We, for example, use this to upload crash logs to blob storage and then mail a link to the support team.
So if we would call this method using the following parameters.
We would get a link pointing at http://yourstorageaccount.blob.core.windows.net/folder/file.txt containing the text – “text in file”. Please note that this call is made synchronously.
Upload a Blob from a stream
You will recognize this from the previous example. The difference is that we are using a stream instead of a string and that the call is made asynchronously.
List all Blobs in a container
This will give a list of links to all blobs stored in a container.
Simple enough. Once you got the setup right, Azure Blob Storage is actually quite easy to use. If you would like to list blobs in subfolders as well then use the overloaded method for ListBlobs and send in BlobRequestOptions { UseFlatBlobListing = true }.
Download content from a Blob
Very similar to uploading data, it works the same way with other data types than string.
But, before downloading a blob, you might want to see if it exists…
See if a Blob exists
The only way that I have found for doing this (and please correct me if I’m wrong here) is to do a little peek and catch the resulting exception.
Thanks to Steve Marx for the solution. FetchAttributes() is used simply because it will be a small amount of data transferred or a 404. So even if I call BlobExists() on a 4Mb block blob it won’t be any different from doing the same call on a 2Kb blob.
Some tips and tricks
Well, first of all. Azure Blob storage can be used for much more than just file storage. Scalability is built in so if you, for example, have a static html page, you can easily upload it to Azure blob storage and then link to it. It is a good way to take away load from your WebRole.
All methods that I showed you have a Begin/End method as well. So you should be able to do most of the work asynchronously, as I did when I uploaded a blob from a stream.
If an Azure Queue message risk becoming bigger than 8Kb the recommended solution is to upload the message as a blob and then store the URI as the message on the queue. You won’t get charged for the extra data traffic as long as it’s done within the same data center.
Happy blobbing
No comments:
Post a Comment