Compartir a través de


‘Hello world’ for Windows Azure Blob Storage

 

While learning various storage models for Windows Azure, I was looking for a simple ‘Hello world’ application which will only write to Blob Storage. It turned out that such simple application was not so easy to find on internet for a newbie, it was at least to me.

So I am sharing one such code snippet which will do a write to Blob storage. This can be used to learn the interaction with Blob storage as your very first step and also it can be used to debug your existing applications deployed in cloud.

A detailed reference can be found here in MSDN

https://www.windowsazure.com/en-us/develop/net/how-to-guides/blob-storage/ 

 

 
public override bool OnStart()
{

   // create a local file to upload
   var fileStream1 = System.IO.File.Create(@"hello.txt");
   fileStream1.Close();


 
   // Retrieve storage account from connection string.
   CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
         CloudConfigurationManager.GetSetting("StorageConnectionString"));
 
    

   // Create the blob client.
   Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient blobClient = 
                    storageAccount.CreateCloudBlobClient();

 
   

   // Retrieve reference to a previously created container.
   CloudBlobContainer container = 
                        blobClient.GetContainerReference("mycontainer");
   container.CreateIfNotExists();
 
 
            

    // Retrieve reference to a blob named "myblob".
    CloudBlockBlob blockBlob = 
                      container.GetBlockBlobReference("OnStartEvent " + "_" 
                     + System.DateTime.Now.ToString() 
                     + "_" + RoleEnvironment.CurrentRoleInstance.Id.ToString());
 
            

   // Create or overwrite the "myblob" blob with contents from a local file.
   using (var fileStream = System.IO.File.OpenRead(@"hello.txt"))
   {
            blockBlob.UploadFromStream(fileStream);
   }
 
 
 
   return base.OnStart();
 
 }
  
  
 The prerequisites are 
 1. You should have a valid Windows Azure subscription 
                                               (get your 30 days free trial here)
 2. You have created a Storage on the portal (Azure Portal –> New –> 
                                  Data Services –> Storage –> Quick Create)
 3. Have configured a connection string in your config file 
                                           (web.config or app.config)
  
 <configuration>
<appSettings>
<add key="StorageConnectionString" 
value="DefaultEndpointsProtocol=https;
         AccountName=[AccountName];
         AccountKey=[AccountKey]" />
</appSettings>
</configuration>
  
 Now you should be able to build and perform this simple interaction with Azure Blob Storage. To see the storage data, you can use 
 Azure Storage Explorer
 or
 Visual Studio (if using Azure SDK 2.0) 
  
 Hope this helps!