Implement Azure File Storage Using ASP.NET Core Console Application

Introduction 

 
In this article we will discuss how to develop a web application or console-based application to store data into the Azure File Storage. We all know that File Storage is a part of Azure Storage. So first, we will discuss some basic concepts about Azure file storage and then we will discuss how to store data into the Azure file storage.
 
Microsoft provides four different types of storage within the Azure Storage except for Azure SQL and Azure Cosmos DB. Azure Storage accounts provide four different types of data services through which we can save data into the Azure storage accounts. The below image shows all the elements of Azure Storage.
 
Implement Azure File Storage Using ASP.NET Core Console Application
 

Concept of Azure File Storage

 
Microsoft announced the Azure File Storage concept in the year of 2015. With the help of Azure File Storage, Microsoft Azure can provide us fully managed file shares in the cloud environment, since Azure File Storage exposed the file share mechanism using the Server Message Block 3.0 (SMB) protocol. This protocol is predominantly used in the file share process for any existing on-premises applications. So, in this way, it is very easy to move our application from the on-premises environment to the cloud environments. Azure File Storage can also implement by REST API protocol, which provides us the means to develop any modern application which needs to integrate with existing applications.
 
Azure File Storage is designed to support different types of business scenarios:
  1. Migrating an existing application from the on-premises environment to the cloud. Azure File Storage provides us an option to migrate our on-premises file or file share-based applications to the Cloud environment without managing any highly-available file server VMs.
  2. Customers can share server data across on-premises and cloud servers. Many applications now store data such as log files, event data, and backups in the cloud environment to achieve better availability, durability, scalability, and geo-redundancy. So, with the encryption in SMB 3.0, we can securely mount Azure File Storage shared from anywhere.
  3. We can integrate modern applications with the help of Azure File Storage.
  4. We can simplify the hosting high availability (HA) workload data with the help of Azure File Storage. Since Azure File Storage provides continuous availability, it simplifies the effort to host HA workload data in the cloud.

Benefits of Azure File Storage

 
So, the main benefits of the Azure File Storage are:
  • Azure File Storage is much more secure because our data is encrypted at rest and during transit, either SMB 3.0 or HTTPS protocol is used for the data.
  • Azure File Storage is much smarter since we can access our files over high latency. Also, we can access the files in low bandwidth links using smart caching of commonly used on-premises files using Azure File Sync.
  • Azure File Systems supports Cross-Platform. We can mount our Azure File Share from Windows, Linux, or macOS based server also.
  • Azure File Systems can be easily managed since the deployment of Azure File Server does not require any hardware or operating system related to deployment management. So, we can directly focus on our users instead of hardware or operating system management.
  • We can implement Azure File Server in a Hydrid model like we can access our data from anywhere we want with the help of SMB, REST, or even on-premises with Azure File Sync.
  • We can directly migrate our file share-dependent application to the cloud without breaking or changing the existing code.
Implement Azure File Storage Using ASP.NET Core Console Application
Perquisites Required
  1. Microsoft Visual Studio 2017
  2. The account in Azure Portal.
If you don’t have any existing Azure account, then you can create a free trial account in the Azure portal using your email ID.
 

Upload Files in Azure File Storage Account using Azure Portal or Powershell

 
For using Azure File Storage, we first need to create a Storage Accounts in Azure Portal. Once the Storage Account has been created, click on the account to open in Storage Account Explorer.
 
Step 1
 
Now click on the File Share option in the Storage Explorer.
 
Implement Azure File Storage Using ASP.NET Core Console Application
 
Step 2
 
Now in File Share, click on the File Share button to create an Azure File Share Endpoint.
 
Implement Azure File Storage Using ASP.NET Core Console Application
 
Step 3
 
Provide the File Share account name and also we can provide the Quota (i.e. the maximum size allocation of the File Share). Initially we provide 2 GB. Later we can increase or decrease the quota volume.
 
Implement Azure File Storage Using ASP.NET Core Console Application
 
Step 4
 
Now in the File Share list, click on the File Share which we just created. It will open the File Share Access point. In that window, click on the Connect button to retrieve the connection string. With the help of this connection command, we can mount the Azure File Share account as a drive from our windows or any other OS based computers.
 
Implement Azure File Storage Using ASP.NET Core Console Application
 
Step 5
 
Now copy the above script and execute it in the Powershell window. After running the script, Azure File Storage is mounted in the computer as Z drive.
 
Implement Azure File Storage Using ASP.NET Core Console Application
 
Step 6
 
Now, we can create any files as we want and it will be automatically uploaded in the Azure File Storage account. Every file uploaded in the Azure File Storage account will provide a public URL through which we can access that file.
 
Implement Azure File Storage Using ASP.NET Core Console Application
 

Upload Files in Azure File Share using .NET Core Console Application

 
Step 1
 
Now open Microsoft Visual Studio 2017 and click on File --> New --> Projects.
 
Step 2
 
Select Console App Project template and Click on the Ok Button
 
Step 3 
 
Before we start coding, we first need to install some packages which help us to implement Azure File Storage in the console applications.
 
Step 4 
 
So, in the Solution Explorer, right-click to our project and choose Manage Nuget Packages.
 
Step 5 
 
Now, in the Nuget Package Manager, select Browse.
 
Step 6 
 
Now, search for the Package Microsoft.Azure.Storage.Blob and then Install.
 
Step 7 
 
Similarly, install the below packages:
  • Microsoft.Azure.Storage.Common
  • Microsoft.Azure.Storage.File
  • Microsoft.Azure.ConfigurationManager
Implement Azure File Storage Using ASP.NET Core Console Application
 
Step 8
 
Now Open the App.config file and add the connection string related to the Azure File Share. In the Connection String, replace the accountName with Azure Storage Account name and keyName with the Azure Storage Account key.
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <configuration>  
  3.   <appSettings>  
  4.     <add key="fileShareConnectionString"value="DefaultEndpointsProtocol=https;AccountName=accountName;AccountKey=keyName" />  
  5.     <add key="fileShareConnectionString" value="DefaultEndpointsProtocol=https;AccountName=cloudshell494327991;AccountKey=v87L6Zor0sEHjL0CeU7i8ujiVW+eU+9vorCQIP/Q0mCEJnihQYOJVfIiRDxYe1450+ksn+R2HbhByYPhcB2Etg==" />  
  6.   </appSettings>  
  7. </configuration>  
Step 9
 
Write the below code to access the File Storage account in Azure. With the help of this code, we can access the Log.txt file from the Azure File Share account and display the content of the file into the console.
  1. static void Main(string[] args)  
  2.         {    
  3.             //code for retrieving the connection string  
  4.             CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("fileShareConnectionString"));  
  5.               
  6.             CloudFileClient cloudFileClient = storageAccount.CreateCloudFileClient();  
  7.   
  8.             // Get a reference to the file share we created previously.  
  9.             CloudFileShare fileShare = cloudFileClient.GetShareReference("filesharedemo");  
  10.   
  11.             // Ensure that the share exists.  
  12.             if (fileShare.Exists())  
  13.             {  
  14.                 // Get a reference to the root directory for the share.  
  15.                 CloudFileDirectory fileDirectory = fileShare.GetRootDirectoryReference();  
  16.   
  17.                 // Get a reference to the directory we created previously.  
  18.                 CloudFileDirectory customDirectory = fileDirectory.GetDirectoryReference("CustomDocs");  
  19.   
  20.                 // Ensure that the directory exists.  
  21.                 if (customDirectory.Exists())  
  22.                 {  
  23.                     // Get a reference to the file we created previously.  
  24.                     CloudFile fileInfo = customDirectory.GetFileReference("Log1.txt");  
  25.   
  26.                     // Ensure that the file exists.  
  27.                     if (fileInfo.Exists())  
  28.                     {  
  29.                         // Write the contents of the file to the console window.  
  30.                         Console.WriteLine(fileInfo.DownloadTextAsync().Result);  
  31.                     }  
  32.                 }  
  33.   
  34.                 NewFileCreate();  
  35.             }  
  36.         }  
Step 10 
 
Now, Execute the program to check the output.
 
Implement Azure File Storage Using ASP.NET Core Console Application
Step 11 
 
In the next part, we will try to create a new file programmatically. To create a new file, we need to define or generate a Shared Access Signature (SAS) for a file share or an individual file. We can also create the access policy for a file share to manage the shared access signature. In the below section, we create a stored access policy on the file share. This example uses that policy to provide the constraints for a SAS on a file in the share.
  1. public static void NewFileCreate()  
  2.         {  
  3.             CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("fileShareConnectionString"));  
  4.             
  5.             CloudFileClient fileClient = storageAccount.CreateCloudFileClient();  
  6.             CloudFileShare share = fileClient.GetShareReference("filesharedemo");  
  7.             // Ensure that the share exists.  
  8.             if (share.Exists())  
  9.             {  
  10.                 string policyName = "sampleSharePolicy" + DateTime.UtcNow.Ticks;  
  11.                  
  12.                 SharedAccessFilePolicy sharedPolicy = new SharedAccessFilePolicy()  
  13.                 {  
  14.                     SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),  
  15.                     Permissions = SharedAccessFilePermissions.Read | SharedAccessFilePermissions.Write  
  16.                 };  
  17.   
  18.                 FileSharePermissions permissions = share.GetPermissions();  
  19.                   
  20.                 permissions.SharedAccessPolicies.Add(policyName, sharedPolicy);  
  21.                 share.SetPermissions(permissions);  
  22.                   
  23.                 CloudFileDirectory rootDir = share.GetRootDirectoryReference();  
  24.                 CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("CustomDocs");  
  25.   
  26.                 CloudFile file = sampleDir.GetFileReference("Log1.txt");  
  27.                 string sasToken = file.GetSharedAccessSignature(null, policyName);  
  28.                 Uri fileSasUri = new Uri(file.StorageUri.PrimaryUri.ToString() + sasToken);  
  29.                   
  30.                 // Create a new CloudFile object from the SAS, and write some text to the file.  
  31.                 CloudFile fileSas = new CloudFile(fileSasUri);  
  32.                 fileSas.UploadText("This file created by the Console App at Runtime");  
  33.                 Console.WriteLine(fileSas.DownloadText());  
  34.             }  
  35.         }  
Step 12 
 
Now execute the program and check the File Share explorer in Azure Portal.
 
Implement Azure File Storage Using ASP.NET Core Console Application
 

Conclusion

 
In this article, we discuss how to store data using the ASP.NET Core application in Azure File Storage. Any suggestions or feedback related to this article are most welcome.
 
Also, if anybody wants to read the other articles related to the Azure Storage, then follow the below links,