Adventures with Azure Storage: Accessing a File with a Shared Access Signature

azure storage

In this post we will look at how to read a document stored in Azure Storage, specifically in an Azure File Share, using .NET Core 2.2 and Shared Access Signature (SAS).

This article assumes you have an Azure Account and an Azure Storage Account.

Create an Azure File Share in your Azure Storage Account, which you can follow along at https://blogs.msdn.microsoft.com/jpsanders/2017/10/12/easily-create-a-sas-to-download-a-file-from-azure-storage-using-azure-storage-explorer, but instead of Blobs, do the same for Files.

Add a File share called files, and upload a test file, for my example, I uploaded a file called test.json.

In Visual Studio or VS Code, create a .NET Core Console App.

Add the nuget packages Microsoft.Azure.Storage.Common and Microsoft.Azure.Storage.File to your project. These packages allow for easy access to Azure Storage.

Add an appsettings.Development.json file.

Open Azure Storage Explorer and right click on the Storage Account folder where you upload the test.json file.

Click Get Shared Access Signature.

On the next screen, click Create.

On the next screen, click Copy to copy the Connection String.

Update the appsettings.Development.json file with the Connection String.

{
    "AzureStorageOptions": {
        "ConnectionString": "YOUR_SAS_CONNECTION_STRING"
    }
}

In the Program.cs file add the following using directives:

using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.File;
using Microsoft.Extensions.Configuration;
using System;

Replace the contents of Main with the following:

var configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddJsonFile("appsettings.Development.json")
    .Build();

var storageAccount = CloudStorageAccount.Parse(
    configuration["AzureStorageOptions:ConnectionString"]);
var fileClient = 
    storageAccount.CreateCloudFileClient();
var share = 
    fileClient.GetShareReference("files");

var directory = share.GetRootDirectoryReference();

var file = directory.GetFileReference("test.json");

Console.WriteLine(file.Uri);
Console.WriteLine(file.DownloadText());

Console.Write("Press any key to exit...");
Console.Read();

Run your app and you should see the contents of the test.json file displayed in the window.

That’s it! Let me know if that helps you out or if you have some feedback on how to make it better!

The code for this example can be found at https://github.com/mattruma/SampleAzureStorageApps/tree/master/SampleAzureStorageFileConsoleApp.

Related Links

Leave a Reply

Your email address will not be published.