In this blog, I am going to describe and walk through the method that can be used to retrieve/fetch files from Azure Storage programmatically. Let's jump right into it.

Azure Files

Azure Files offers fully managed file shares in the cloud that are accessible via the industry standard Server Message Block (SMB) protocol or Network File System (NFS) protocol. Some of the common applications of Azure Files would include serving as a replacement for on-premises file servers, persistent volumes for stateful containers, storing application logs, migrating applications, etc.

Pre-Requisites

We need the following for the code covered in this article to work,

Implementation

Assuming that all the pre-requisites are now ready, we will begin the actual code implementation to connect to our Azure Files and collect the required files/folder details from there using a C# (.Net Core) based code.

Step 1 - Create the Console App

Step 2 - Add the required packages

Step 3

Create the method GetAllFilesFromDirectory.

C#
private static List<IListFileItem> GetAllFilesFromDirectory(CloudFileDirectory directory)
{
    List<IListFileItem> results = new List<IListFileItem>();
    FileContinuationToken token = null;
    do
    {
       FileResultSegment resultSegment = directory.ListFilesAndDirectoriesSegmentedAsync(token).GetAwaiter().GetResult();
       token = resultSegment.ContinuationToken;
    }
    while (token != null);
    return results;
}

Step 4

Include the below references in Program.cs file.

C#
using System;
using System.Collections.Generic;
using Microsoft.Azure.Storage.File;
using Microsoft.Azure.Storage;

Step 5

Modify the Main in Program.cs file.

C#
static void Main(string[] args) {
    string connectionString = @ "your-SAS-connection-string-saved-in-pre-requisites";
    CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(connectionString);
    CloudFileClient cloudFileClient = cloudStorageAccount.CreateCloudFileClient();
    CloudFileShare cloudFileShare = cloudFileClient.GetShareReference("your-file-share-name");
    CloudFileDirectory rootDirectory = cloudFileShare.GetRootDirectoryReference();
    CloudFileDirectory fileDirectory = rootDirectory.GetDirectoryReference("your-file-share-folder-name");
    List < IListFileItem > fileList = GetAllFilesFromDirectory(fileDirectory);
    Console.WriteLine("File Count in folder " + cloudFileShare.Name + " is : " + fileList.Count);
    //Console.WriteLine("Hello World!");
}

Now our code is ready for execution. When you run this console now, you should see in output file share name and the count of files. We are just printing out the number of files within our Azure File Share as part of this code but you can modify and use the collection of files that we have obtained and stored in the list (fileList object) returned by the program execution based on your business needs and requirements.

Happy Coding!