Showing posts with label Azure blob. Show all posts
Showing posts with label Azure blob. Show all posts

Wednesday, September 30, 2015

Reading data from Azure Storage Blob into a string

The code below I used to read the text from the file located on Azure blob into a string:
string filename ="mytargetfile.txt"
string blobConn = CloudConfigurationManager.GetSetting("BlobConn");
CloudStorageAccount storageAcct = CloudStorageAccount.Parse(blobConn);
CloudBlobClient blobClient = storageAcct.CreateCloudBlobClient();
CloudBlobContainer blobContainer = blobClient.GetContainerReference("container1");
if (blobContainer.Exists(null, null))
{
    CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(filename);
    if (blockBlob.Exists(null, null))
    {
         //read data from the blob into a stream and get it into an array
         using (var ms = new MemoryStream())
        {
             blockBlob.DownloadToStream(ms);
             ms.Position = 0;
             using (var reader = new StreamReader(ms, Encoding.Unicode))
             {
                   var fileText = reader.ReadToEnd();
             }
        }
    }
}




Tuesday, September 29, 2015

Saving file from Azure Storage Blob onto a hard drive using C#

Recently started working with Azure storage blob. So far I am really enjoying it so I wanted to share some code snippet I have wrote so far for various purposes. The one below I have used to save the file from the blob onto my hard drive.
//reading blob file data into a file on your hard drive
string filename ="mytargetfile.txt"
string blobConn = CloudConfigurationManager.GetSetting("BlobConn");
CloudStorageAccount storageAcct = CloudStorageAccount.Parse(blobConn);
CloudBlobClient blobClient = storageAcct.CreateCloudBlobClient();
CloudBlobContainer blobContainer = blobClient.GetContainerReference("container1");
if (blobContainer.Exists(null, null))
{
     CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(filename);
     if (blockBlob.Exists(null, null))
    {
          string tempFile = Path.Combine(@"C:\BlobFiles",filename);
          blockBlob.DownloadToFile(tempFile, FileMode.Create);
    }
}