Skip to content

Instantly share code, notes, and snippets.

@andrijac
Created July 7, 2014 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrijac/edb0fb87271721fddfdd to your computer and use it in GitHub Desktop.
Save andrijac/edb0fb87271721fddfdd to your computer and use it in GitHub Desktop.
Azure storage manager (Block Blob)
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