Joydip Kanjilal
Contributor

How to work with Azure file storage in C#

how-to
Aug 27, 20185 mins
Cloud ComputingSmall and Medium BusinessSoftware Development

Take advantage of Azure Files in your .Net applications to access managed, secure, SMB file shares in the Microsoft Azure cloud

cloud contracts thinkstock
Credit: Thinkstock

Microsoft’s Azure cloud computing platform provides interoperable cloud computing services that are comprised of both open source and standards-based technologies. Case in point: Azure Files are managed file shares that you can access using the SMB (Server Message Block) protocol. The SMB protocol is used to provide shared access to resources like files, printers, and serial ports over a network. This article examines how we can work with Azure Files using .Net.

The Azure Storage services include shares, directories, and files. A share may be defined as a logical representation of drives that can be mapped. A share comprises of one or more directories. Each directory comprises of one or more files. This relationship is depicted in Figure 1.

azure file storage figure 1 IDG

Figure 1: Shares, directories, and files in an Azure Storage account.

Getting started with Azure Storage

To work with files, queues, tables, and disks in Azure, you should have an Azure storage account. Essentially, an Azure Storage account is a unique namespace in the Azure cloud that can be used for storage and retrieval of data.

In his section we will explore how we can setup an Azure file share using the Azure portal. To create a storage account, follow these steps.

  1. In the Azure Portal, select “Create a resource”
  2. Next, click on Storage -> “Storage account – blob, file, table, queue” as shown in Figure 2 below
  3. In the form window that opens (see Figure 3 below), specify a name for the storage account
  4. Select the replication option you would like to use
  5. Select the subscription
  6. Click Create
azure file storage figure 2 IDG

Figure 2: Creating a resource in the Azure portal. 

azure file storage figure 3 IDG

Figure 3: Creating a storage account in the Azure portal. 

Once the storage account has been created successfully, you’ll see the appropriate notification in the Azure portal. Browsing your new storage account, locate the Files option and click on File Share to create a new file share. Specify the name and quota for the file share as appropriate.

azure file storage figure 4 IDG

Figure 4: Creating a new file share in the Azure Portal. 

Once the file share has been created, create a directory to store your files and then upload a few files into the directory. You can also map a network drive in your computer to the storage account. Now let’s explore how we can connect to Azure Files storage and download and upload content.

Access Azure Files programmatically in C#

In this section we’ll discuss how we can access an Azure Files file share programmatically. First off, follow the steps given below to create a console application project in Visual Studio.

  1. Open your Visual Studio IDE
  2. Select File -> New -> Project
  3. From the installed templates, select Visual C# -> Windows Classic Desktop
  4. Choose Console App (.Net Framework)
  5. Specify a name for your project
  6. Click OK

To work with Azure files in .Net, you should install the Microsoft.WindowsAzure.ConfigurationManager and WindowsAzure.Storage packages from NuGet. While the former provides a unified API for loading the configuration settings, the latter is a client library that is used to work with Azure storage services to store and retrieve non-relational data.  

You can install each of these libraries via the NuGet Package Manager UI in Visual Studio. Alternatively, you can enter the following commands in the NuGet Package Manager Console window as shown in the code snippet below.

PM> Install-Package WindowsAzure.Storage
PM> Install-Package Microsoft.WindowsAzure.ConfigurationManager

Retrieving references to Azure storage in C#

The following code snippet can be used to retrieve a reference to the storage account.

CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting(“StorageConnectionString”));

To retrieve a reference to the file share we created earlier, you can use the following code snippet.

CloudFileClient cloudFileClient = 
storageAccount.CreateCloudFileClient();

CloudFileShare cloudFileShare = 
cloudFileClient.GetShareReference("demo");

If you would like to access the directory you created earlier, you should first get a reference to the root directory and then use that reference to access the directory you created. (For this example, I’ll use a directory named demodirectory.) Here’s the code snippet that illustrates how this can be achieved.

CloudFileDirectory rootDir = 
cloudFileShare.GetRootDirectoryReference();

CloudFileDirectory workarea = 
rootDir.GetDirectoryReference("demodirectory");

Download a file from an Azure Files file share in C#

The following code listing puts all of this together into a method that downloads a file from a directory. The connection string, name of the file share, name of the directory, and name of the file to be downloaded should be passed as an argument.

static async Task<string> DownloadFile(string connectionString,
            string fileShareName, string directoryName,
            string fileName)
        {
            CloudStorageAccount storageAccount = 
CloudStorageAccount.Parse(connectionString);
            CloudFileClient cloudFileClient = storageAccount.CreateCloudFileClient();
            CloudFileShare cloudFileShare = 
cloudFileClient.GetShareReference(fileShareName);
            if (cloudFileShare.Exists())
            {
                CloudFileDirectory rootDir = cloudFileShare.GetRootDirectoryReference();
                CloudFileDirectory workarea = 
rootDir.GetDirectoryReference(directoryName);
                if (workarea.Exists())
                {
                    CloudFile cloudFile = workarea.GetFileReference(fileName);
                    if (cloudFile.Exists())
                    {
                        return await cloudFile.DownloadTextAsync();
                    }
                }
            }
            return null;
        }

Finally, here is how the DownloadFile method can be called.

static string connectionString = "Some connection string...";
        static void Main(string[] args)
        {
            Console.Write(DownloadFile(connectionString, "demo",
                "demodirectory", "Test.txt").Result);
            Console.Read();
        }

Azure Files let’s you take advantage of managed file shares in the cloud from your .Net applications, allowing users to access file content from wherever they may be. With the availability of the REST API to access Azure Files storage, you can even integrate your legacy applications with your modern-day applications. In one of my future articles here I will demonstrate working with Azure Files via the REST API.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author