Created
July 7, 2014 13:54
-
-
Save andrijac/edb0fb87271721fddfdd to your computer and use it in GitHub Desktop.
Azure storage manager (Block Blob)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using Microsoft.WindowsAzure; | |
using Microsoft.WindowsAzure.Storage; | |
using Microsoft.WindowsAzure.Storage.Blob; | |
namespace AzureProject | |
{ | |
public class AzureStorageManager | |
{ | |
private CloudBlobClient blobClient; | |
public AzureStorageManager() | |
{ | |
this.InitiateBlobClient(); | |
} | |
public void UploadFile(string containerName, Stream uploadStream, string storageName) | |
{ | |
CloudBlobContainer container = this.GetContainer(containerName); | |
CloudBlockBlob blockBlob = container.GetBlockBlobReference(storageName); | |
blockBlob.UploadFromStream(uploadStream); | |
} | |
public byte[] DownloadFile(string containerName, string storageName) | |
{ | |
// Retrieve reference to a previously created container. | |
CloudBlobContainer container = this.GetContainer(containerName); | |
// Retrieve reference to a blob named "photo1.jpg". | |
CloudBlockBlob blockBlob = container.GetBlockBlobReference(storageName); | |
using (Stream storageStream = new MemoryStream()) | |
{ | |
blockBlob.DownloadToStream(storageStream); | |
storageStream.Position = 0; | |
byte[] buffer = new byte[16 * 1024]; | |
using (MemoryStream ms = new MemoryStream()) | |
{ | |
int read; | |
while ((read = storageStream.Read(buffer, 0, buffer.Length)) > 0) | |
{ | |
ms.Write(buffer, 0, read); | |
} | |
return ms.ToArray(); | |
} | |
} | |
} | |
private CloudBlobContainer GetContainer(string containerName) | |
{ | |
CloudBlobContainer container = this.blobClient.GetContainerReference(containerName); | |
container.CreateIfNotExists(); | |
return container; | |
} | |
private void InitiateBlobClient() | |
{ | |
string storageConnectionString = CloudConfigurationManager.GetSetting("StorageConnection"); | |
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString); | |
this.blobClient = storageAccount.CreateCloudBlobClient(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment