Utilisation du storage Azure

A travers ce post vous verrez comment stocker très facilement vos fichiers sur azure.

Pour commencer, il faut créer sur azure le compte de stockage.

Azure 1

A l’intérieur de celui-ci, il faut maintenant créer le conteneur.

azure 4

Maintenant avant de vous déconnectez de votre compte azure prenez note des infos de connexion.

Le « storage account name » sera la valeur pour la propriété AccountName.

La « primary access key » sera la valeur pour la propriété KeyValue.

Le nom du conteneur sera la valeur pour la propriété ContainerName.

azure 2

Ça y est vous êtes prêt à stocker vos documents dans azure. Nous allons pour se faire créer une DLL qui contiendra des méthodes afin d’uploader, supprimer et télécharger des documents.

Créer donc une application de type class library et ajouter via nugget le package Windows Azure Storage.

azure 3

Dans une classe appelé FileStorage, nous allons créer une série de méthodes privé que nous pourrons appeler par la suite pour effectuer ce que nous désirons. Il s’agit des méthodes qui permettent d’établir la connexion sur votre compte de stockage.


public static class FileStorage
    {
        #region Private Method
        private static CloudBlobContainer GetContainer(CloudBlobClient blobClient, string containerName)
        {
            return blobClient.GetContainerReference(containerName);
        }

        private static CloudBlobClient InitializeAzureConnection(StorageInformation storageInformation)
        {
            var storageCredential = new StorageCredentials(storageInformation.AccountName, storageInformation.KeyValue);
            var storageAccount = new CloudStorageAccount(storageCredential, true);
            return storageAccount.CreateCloudBlobClient();
        }
        private static CloudBlockBlob GetCloudBlockBlob(CloudBlobContainer cloudBlobContainer)
        {
            var guid = Guid.NewGuid();
            return cloudBlobContainer.GetBlockBlobReference(guid.ToString());
        }
        private static CloudBlockBlob InitializeForUpload(StorageInformation storageInformation)
        {
            var blobClient = InitializeAzureConnection(storageInformation);
            var container = GetContainer(blobClient, storageInformation.ContainerName);
            return GetCloudBlockBlob(container);
        }
        #endregion       
    }

Ensuite nous allons créer les méthodes public que nous pourrons utiliser.


 #region Public Method
        /// <summary>
        /// Upload file from disk to Azure
        /// </summary>
        /// <param name="path"></param>
        /// <param name="storageInformation"></param>
        /// <returns></returns>       
        public static string UploadOnAzure(string path, StorageInformation storageInformation)
        {
            using (var fileStream = File.OpenRead(path))
            {
                var blob = InitializeForUpload(storageInformation);
                blob.UploadFromStream(fileStream);
                return blob.Name;
            }
        }
        /// <summary>
        /// Upload file from stream to Azure
        /// </summary>
        /// <param name="file"></param>
        /// <param name="storageInformation"></param>
        /// <returns>return the real name of your file on Azure (guid)</returns>
        public static string UploadOnAzure(Stream file, StorageInformation storageInformation)
        {
            var binary = new BinaryReader(file);
            var binData = binary.ReadBytes((int)file.Length);
            var blob = InitializeForUpload(storageInformation);
            blob.UploadFromByteArray(binData, 0, binData.Length);
            return blob.Name;
        }
        /// <summary>
        /// Get all file name from your Azure storage 
        /// </summary>
        /// <param name="storageInformation"></param>
        /// <returns>retrun list of file name</returns>
        public static List<string> GetFilesName(StorageInformation storageInformation)
        {
            var blobClient = InitializeAzureConnection(storageInformation);
            var container = GetContainer(blobClient, storageInformation.ContainerName);
            return container.ListBlobs().Select(blobItem => blobItem.Uri.ToString().Substring(blobItem.Uri.ToString().LastIndexOf('/') + 1)).ToList();
        }
        public static void DeleteFile(string nameFile, StorageInformation storageInformation)
        {
            var blobClient = InitializeAzureConnection(storageInformation);
            var container = GetContainer(blobClient, storageInformation.ContainerName);
            var file = container.GetBlockBlobReference(nameFile);
            file.DeleteIfExists();
        }

        public static void DeleteAllFile(StorageInformation storageInformation)
        {
            var fileList = FileStorage.GetFilesName(storageInformation);
            foreach (string fileName in fileList)
            {
                FileStorage.DeleteFile(fileName, storageInformation);
            }
        }
      
        public static FileStreamResult DownloadFile(string nameFile, string realName, string contentType, StorageInformation storageInformation)
        {
            var blobClient = InitializeAzureConnection(storageInformation);
            var container = GetContainer(blobClient, storageInformation.ContainerName);
            var file = container.GetBlockBlobReference(nameFile);

            var stream = new MemoryStream { Position = 0 };
            file.DownloadToStream(stream);
            var result = new FileStreamResult(stream, contentType);
            stream.Position = 0;
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(realName, Encoding.UTF8));
            return result;

        }
        #endregion      

Comme vous pouvez le constater, j’utilise un objet StorageInformation. Cet objet a pour but de contenir les infos utile du compte Azure.

public class StorageInformation
    {
        public string AccountName { get; set; }
        public string KeyValue { get; set; }
        public string ContainerName { get; set; }
    }

Du coup coté client, on va rajouter une classe AzureInformation qui va se charger de récupérer les informations et retourner un objet StorageInformation.

 public static class AzureInformation
    {
        #region Private Method
        private static string GetAccountName()
        {
            return Properties.Settings.Default.AccountName;
        }
        private static string GetContainerName()
        {
            return Properties.Settings.Default.ContainerName;
        }
        private static string GetKeyValue()
        {
            return Properties.Settings.Default.KeyValue;
        }
        #endregion


        #region Public Method
        public static StorageInformation Get()
        {
            var storageInformation =
               new StorageInformation
               {
                   AccountName = GetAccountName(),
                   ContainerName = GetContainerName(),
                   KeyValue = GetKeyValue()
               };
            return storageInformation;
        }
        #endregion

    }

Il vous sera facile d’adapter les méthodes privées afin de récupérer les infos selon l’endroits on vous désirez les stocker.

Et voila maintenant dans une application cliente en une ligne de code vous pouvez faire le nécessaire.


var fileNameAzure = FileStorage.UploadOnAzure(txtPath.Text, AzureInformation.Get());

La méthode renvoie le nom du fichier sur Azure.J’ai choisis de générer un guid qu’il vous faudra sauvegarder tout comme le contentType.
Exemple : vous sauvegarder dans une base de donnée l’association du vrai nom de fichier avec le contentType et le guid.

D’autre méthode sont également disponible le code complet est disponible ici.

https://github.com/michelcedric/StorageAzure

Laisser un commentaire

Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur la façon dont les données de vos commentaires sont traitées.