Upload File To Azure File Storage Using C#

Hello Friends, In this article, we will discuss how to upload files into Azure File Storage using C#. We all know that File Storage is a part of Azure Storage. Azure File Storage provides an option to migrate file share-based applications to the Cloud environment without managing any highly available file server VMs.

Step 1 :

Open NuGet Package Manager and search for Package Microsoft.Azure.Storage.Blob and then Install.

Step 2 :

Similarly, install the below packages:

Microsoft.Azure.Storage.Common
Microsoft.Azure.Storage.File
Microsoft.Azure.ConfigurationManager

 

Step 3 :

Now Open the App.config file and add the connection string for Azure Storage. In the Connection String, replace the accountName with the Azure Storage Account name and keyName with the Azure Storage Account key.

<?xml version="1.0" encoding="utf-8" ?>  
<configuration>  
  <appSettings>  
    <add key="StorageAccountConnectionString"value="DefaultEndpointsProtocol=https;AccountName=<accountName>;AccountKey=<keyName>" />  
  </appSettings>  
</configuration>

Step 4:

Now, add we create a new API endpoint for file upload looks like below. we get the files using Request Form data and converted them to Stream and called SaveFileAzure to upload files into the Azure File Storage account.

[HttpPost("fileupload")]
public IActionResult Upload()
{
    try
    {
        var file = Request.Form.Files[0];
        if (file.Length > 0)
        {
            Stream fileStream = file.OpenReadStream();
            string extension = System.IO.Path.GetExtension(file.FileName);
            var uri = SaveFileAzure(fileStream, extension);
            return Ok(new { uri });
        }
        else
        {
            return BadRequest();
        }
    }
    catch (Exception ex)
    {
        return StatusCode(500, $"Internal server error: {ex}");
    }
}

Step 5:

Now, we add a new method for upload files in the Azure File Storage account.

We need to Storage Account for file upload we get from the connection string.

private string SaveFileAzure(Stream inputStream, string extension)
{
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(StorageAccountConnectionString);

    CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
    CloudFileShare share = fileClient.GetShareReference("codeHubs");
    // Ensure that the share exists.  
    if (share.Exists())
    {
    string policyName = "fileStorageSharePolicy" + DateTime.UtcNow.Ticks;  
                 
        SharedAccessFilePolicy sharedPolicy = new SharedAccessFilePolicy()  
        {  
            SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),  
            Permissions = SharedAccessFilePermissions.Read | SharedAccessFilePermissions.Write  
        };  
  
        FileSharePermissions permissions = share.GetPermissions();  
          
        permissions.SharedAccessPolicies.Add(policyName, sharedPolicy);  
        share.SetPermissions(permissions);  
        
        CloudFileDirectory rootDir = share.GetRootDirectoryReference();
        CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("FileStorage");
        string fileName = Guid.NewGuid().ToString();
        var cloudFile = sampleDir.GetFileReference($"{fileName}{extension}");

        cloudFile.UploadFromStream(inputStream);

        return cloudFile.Uri.ToString();
    }
    else
    {
        return String.Empty;
    }
}

SaveFileAzure method returns the uploaded file URI.

I hope this article helps you and you will like it.

Submit a Comment

Your email address will not be published. Required fields are marked *

Footer Logo

Subscribe

Select Categories