Saturday, February 21, 2015

Uploading a file to Azure Blob Storage using C#




So I'm in the process of upgrading my blog to be able to upload pictures to the Azure Blob Storage.
Most of the samples I found required alot of XML configuration, or special project types. This post offers a simpler way, that will get you started.
  1. First, you need the NuGet Package "WindowsAzure.Storage".
  2. After that, then ensure that you have a storage account on Azure, and that you created a public container.
  3. Find you account name and primary access key (There is a icon called manage keys at the bottom of the screen of the mangement portal)
  4. Take the code snippet below and add your values (remember to edit the file path to a file that exists):
 
 var credentials = new StorageCredentials("deldysoft", "YOUR PRIMARY KEY FROM. GET IT FROM THE MANGEMENT PORTAL");

var client = new CloudBlobClient(new Uri("http://deldysoft.blob.core.windows.net/"), credentials);

// Retrieve a reference to a container. (You need to create one using the mangement portal, or call container.CreateIfNotExists())
var container = client.GetContainerReference("deldydk");

// Retrieve reference to a blob named "myfile.gif".
var blockBlob = container.GetBlockBlobReference("myfile.gif");

// Create or overwrite the "myblob" blob with contents from a local file.
using (var fileStream = System.IO.File.OpenRead(@"C:\\myfile.gif"))
{
  blockBlob.UploadFromStream(fileStream);
}
 
 

Image result for azure logo
 

Thats it! You should now be able to see your blob at the mangement portal.
If you need to list blobs, and other stuff that is porsible, then look at other tutorials on the web or at the Azure Website. You should be able to use the client you created here to skip over all the configuration stuff that many of them include.
Have fun!
 

No comments:

Post a Comment