Access WindowsAzure Storage Account via Asp.net C#

By | May 21, 2014
rx online

In this article we will learn to access the window azure storage account. You will able to uploads the file to blob, delete the file from blob and get the list of files from blob. Microsoft Azure (formerly Windows Azure before March, 25th 2014) is a cloud computing platform and infrastructure, created by Microsoft, for building, deploying and managing applications and services through a global network of Microsoft-managed datacenters. It provides both PaaS and IaaS services and supports many different programming languages, tools and frameworks, including both Microsoft-specific and third-party software and systems To access the window azure storage account you need Account Name and Account key for authentication, once you get this information you will able to connect to window azure storage account easily. Also, you required to add reference of “Microsoft.WindowsAzure.Storage” in your project. You can download this library from here. I have creates the simple class WindowAzureLib which  will perform all action like UploadFiles, GetListOfFiles, Download Files, DeleteFiles from blob. Provided below are the code for the same:

using System;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage;
using System.Data;
using System.IO;

namespace WinAzureUtility
{
    public class WindowAzureLib
    {
        public static CloudStorageAccount _storageAccount = null;
        public static string _partitionKey = string.Empty;
        public static string _id = string.Empty;



        private CloudBlobContainer AuthenticateKey(string AccountName, string AccountKey)
        {
            _storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=" + AccountName + ";AccountKey=" + AccountKey);
            CloudBlobClient blobClient = _storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container = blobClient.GetContainerReference("container");
            container.CreateIfNotExists();
            return container;
        }

        public void InserData(string AccountName, string AccountKey, string fileName, byte[] bytes)
        {
            try
            {
                CloudBlobContainer container = AuthenticateKey(AccountName, AccountKey);
                // Retrieve reference to a blob
                CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);
                using (var stream = new MemoryStream(bytes, writable: false))
                {
                    blockBlob.UploadFromStream(stream);
                }
               
            }
            catch
            {
                throw;
            }
        }

        public MemoryStream GetData(string AccountName, string AccountKey, string fileName)
        {
            try
            {
                CloudBlobContainer container = AuthenticateKey(AccountName, AccountKey);
                CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);
                MemoryStream stream = new MemoryStream();
                blockBlob.DownloadToStream(stream);
                return stream;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public DataTable ListData(string AccountName, string AccountKey)
        {
            try
            {

                DataTable dt = new DataTable();
                dt.Columns.Add("FileName", typeof(string));
                dt.Columns.Add("URL", typeof(string));
                dt.Columns.Add("Type", typeof(string));
                dt.Columns.Add("ContentType", typeof(string));
                dt.Columns.Add("Length", typeof(string));

                CloudBlobContainer container = AuthenticateKey(AccountName, AccountKey);
                foreach (IListBlobItem item in container.ListBlobs(null, false))
                {
                    if (item.GetType() == typeof(CloudBlockBlob))
                    {
                        CloudBlockBlob blob = (CloudBlockBlob)item;
                        DataRow dr = dt.NewRow();
                        dr["FileName"] = blob.Name;
                        dr["Length"] = blob.Properties.Length;
                        dr["Type"] = "CloudBlockBlob";
                        dr["ContentType"] = blob.Properties.ContentType;
                        dr["URL"] = blob.Uri;
                        dt.Rows.Add(dr);
                    }
                    else if (item.GetType() == typeof(CloudPageBlob))
                    {
                        CloudPageBlob pageBlob = (CloudPageBlob)item;
                        DataRow dr = dt.NewRow();
                        dr["FileName"] = pageBlob.Name;
                        dr["Length"] = pageBlob.Properties.Length;
                        dr["Type"] = "CloudPageBlob";
                        dr["ContentType"] = pageBlob.Properties.ContentType;
                        dr["URL"] = pageBlob.Uri;
                        dt.Rows.Add(dr);
                    }
                    else if (item.GetType() == typeof(CloudBlobDirectory))
                    {
                        CloudBlobDirectory directory = (CloudBlobDirectory)item;
                        DataRow dr = dt.NewRow();
                        dr["FileName"] = directory.Container.Name;
                        dr["Length"] = "";
                        dr["Type"] = "CloudBlobDirectory";
                        dr["URL"] = directory.Uri;
                        dt.Rows.Add(dr);
                    }
                }
                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void DeleteData(string AccountName, string AccountKey, string fileName)
        {
            try
            {
                CloudBlobContainer container = AuthenticateKey(AccountName, AccountKey);
                CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);
                blockBlob.Delete();
            }
            catch
            {
                throw;
            }
        }
    }
}

In Above class i have created 5 methods

  • AuthenticationKey to verify the Account Name & Key
  • InserData for uploading files to blob
  • MemoryStream GetData to download the file from blob
  • ListData to get the list of files from blob
  • DeleteData to delete the files from blob

Account Name & Key is required to establish the connection with your window azure storage account.  Click here to know how to get the account name and key. Once you have key with you you can access the azure storage account easily. Also, I have created the asp.net sample page which will access this library and perform all the actions

Aspx code

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AzureExplorer.aspx.cs"
    Inherits="AzureExplorerText.AzureExplorer" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <table>
        <tr>
            <td>
                Select File
            </td>
            <td>
                :
            </td>
            <td>
                <asp:FileUpload ID="fileUploader" runat="server" />
            </td>
            <td>
                <asp:Button ID="btnSubmit" runat="server" Text="Upload" OnClick="btnSubmit_Click" />
            </td>
        </tr>
    </table>
    <div>
        <asp:GridView ID="gvList" runat="server" CellPadding="5" ForeColor="#333333" GridLines="Both"
            AutoGenerateColumns="false" onrowcommand="gvList_RowCommand">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            <EditRowStyle BackColor="#999999" />
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#E9E7E2" />
            <SortedAscendingHeaderStyle BackColor="#506C8C" />
            <SortedDescendingCellStyle BackColor="#FFFDF8" />
            <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
            <Columns>
                <asp:BoundField DataField="FileName" HeaderText="File Name" />
                <asp:BoundField DataField="Length" HeaderText="Length" />
                <asp:BoundField DataField="Type" HeaderText="Type" />
                <asp:BoundField DataField="ContentType" HeaderText="Content" />

                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkDownload" runat="server" CommandName="download" CommandArgument='<%# Eval("FileName") %>'
                            Text="Download"> </asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
                  <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkDelete" runat="server" CommandName="deletefile" CommandArgument='<%# Eval("FileName") %>'
                            Text="Delete File"> </asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>


Code Behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WinAzureUtility;
using System.IO;

namespace AzureExplorerText
{
    public partial class AzureExplorer : System.Web.UI.Page
    {
        WindowAzureLib lib = new WindowAzureLib();
        string AccountName = "Your Account Name";
        string AccountKey = "You Account Key";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                loadList();
            }
        }

        protected void loadList()
        {
            gvList.DataSource = lib.ListData(AccountName, AccountKey);
            gvList.DataBind();

        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (fileUploader.HasFile)
            {
                byte[] fileToByte = fileUploader.FileBytes.ToArray();
                lib.InserData(AccountName, AccountKey, fileUploader.FileName, fileToByte);
                loadList();
            }
        }

        protected void gvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string strCommandName = e.CommandName;
            string strCommandArg = e.CommandArgument.ToString();

            switch (strCommandName)
            {
                case "download":
                    MemoryStream fs = lib.GetData(AccountName, AccountKey, strCommandArg);
                    byte[] bytes = fs.ToArray();
                    Response.Clear();
                    Response.ContentType = "application/octet-stream";
                    Response.AppendHeader("Content-Disposition", String.Format("attachment; filename={0}", strCommandArg));
                    Response.OutputStream.Write(bytes, 0, bytes.Length);
                    break;
                case "deletefile":
                    lib.DeleteData(AccountName, AccountKey, strCommandArg);
                    break;
            }
            loadList();
        }
    }
}


Replace your account name & account key with your name and key and you are ready to go.

Hopes this article helped you to achieve your task.

1,237 total views, 1 views today