Upload and Download files from Azure Storage

 

Here is sample code to download and upload files to Azure Storage from Universal Windows Apps.

Complete source code is available here

Introduction to Universal Windows Apps

Visual Studio template for Universal Windows Apps allows developers to build Windows Store App and Phone App in a single Visual Studio solution. This Visual Studio solution includes three projects, project for design and feature experiences unique to Store App, second project for Phone App and third project for shared code.  For more details on Universal Apps template in Visual Studio please click here

Here is the Visual Studio projects for Universal Windows Apps.

UWA_VS

The project ending with .Windows is for Store App, project ending with .WindowsPhone is for Phone App and .Shared is for shared code.

In the Shared Project, use following #defines to write specific code for Phone App or Store App

 
#if WINDOWS_PHONE_APP
    // For Windows Phone App
#elif WINDOWS_APP
    // For Windows Store App
#else
    //  Error
#endif

Introduction to Azure Storage

Azure Storage is storage in cloud which is accessible from anywhere in the world, from any type of application, whether it’s running in the cloud, on the desktop, on an on-premises server, or on a mobile or tablet device. Azure Storage support four types of storage : Blob Storage, Table Storage, Queue Storage and File Storage. For more details please click here.

Steps to create Azure Storage

  1. Login to Azure Portal @ https://manage.windowsazure.com/

  2. Click on New at the bottom left

  3. Select Data Services | Storage | Quick Create and enter URL  as shown below 

    Azure_NewStorage

  4. Next create container, click on Create a Container in the Storage | UniversalAppAzureStorage | Container tab as shown below

    Azure_NewContainer2

  5. Enter a name for container as shown below

    Azure_NewContainerName

  6. Click on Manage Access Keys in the Dashboard tab and copy the Storage Account Name and Primary Access Key as shown

    Azure_StorageKeys2

Steps to create Universal Windows App

  1. Open Visual Studio

  2. Click on File | New

  3. Select Templates | Visual C# | Store Apps | Universal Apps | Hub App as shown

    VS_NewProject

  4. Now install NuGet Package for Azure Store

  5. Right click on the .Windows project and select Manage NuGet Packages

  6. In the search window type Azure Storage as shown below

    NuGet_Package

  7. Click on Install button for Azure Storage

  8. Now install the Azure Storage NuGet Package on .WindowsPhone project

  9. Right click on the .WindowsPhone project and select Manage NuGet Packages

  10. In the search window type Azure Storage and click on the install button

  11. Now lets right code for uploading file to Azure Storage

  12. Open App.xaml.cs file in the .Shared Project

  13. Copy this below upload function

    
           private async Task<int> UploadToAzureStorage()
            {
                try
                {
                    //  create Azure Storage
                    CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=universalappazurestorage;AccountKey=<your key>");
    
                    //  create a blob client.
                    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    
                    //  create a container 
                    CloudBlobContainer container = blobClient.GetContainerReference("containerone");
    
                    //  create a block blob
                    CloudBlockBlob blockBlob = container.GetBlockBlobReference("filename");
    
                    //  create a local file
                    StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("filename", CreationCollisionOption.ReplaceExisting);
    
                    //  copy some txt to local file
                    MemoryStream ms = new MemoryStream();
                    DataContractSerializer serializer = new DataContractSerializer(typeof(string));
                    serializer.WriteObject(ms, "Hello Azure World!!");
    
                    using (Stream fileStream = await file.OpenStreamForWriteAsync())
                    {
                        ms.Seek(0, SeekOrigin.Begin);
                        await ms.CopyToAsync(fileStream);
                        await fileStream.FlushAsync();
                    }
    
                    //  upload to Azure Storage 
                    await blockBlob.UploadFromFileAsync(file);
    
                    return 1;
                }
                catch
                {
                    //  return error
                    return 0;
                }
            }
    
  14. Now copy this below download function

    
            private async Task<int> DownloadFromAzureStorage()
            {
                try
                {
                    //  create Azure Storage
                    CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=universalappazurestorage;AccountKey=<your key>");
    
                    //  create a blob client.
                    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    
                    //  create a container 
                    CloudBlobContainer container = blobClient.GetContainerReference("containerone");
    
                    //  create a block blob
                    CloudBlockBlob blockBlob = container.GetBlockBlobReference("filename");
    
                    //  create a local file
                    StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("filename_from_azure", CreationCollisionOption.ReplaceExisting);
    
                    //  download from Azure Storage
                    await blockBlob.DownloadToFileAsync(file);
    
                    return 1;
                }
                catch
                {
                    //  return error
                    return 0;
                }
            }
    
  15. Now call these two functions

    
            protected async override void OnLaunched(LaunchActivatedEventArgs e)
            {
    #if DEBUG
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    this.DebugSettings.EnableFrameRateCounter = true;
                }
    #endif
                int r = await UploadToAzureStorage();
                if (r == 1)
                {
                    await DownloadFromAzureStorage();
                }
    
                Frame rootFrame = Window.Current.Content as Frame;
    
  16. Run the Windows Store App and check the files local storage

  17. To get the path of the local storage, look at the Path variable value of the StorageFile as shown

    localfilepath

  18. here is the complete source code