Created
February 8, 2018 23:28
-
-
Save justcla/730861300c8db59240bb777cecc66b6b to your computer and use it in GitHub Desktop.
Helper class (C#) returns a list of filenames for all files in a given blob container (Azure Storage)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public async Task<List<string>> GetBlobFileListAsync(string storageConnectionString, string containerName) | |
{ | |
try | |
{ | |
// Get Reference to Blob Container | |
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString); | |
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); | |
CloudBlobContainer container = blobClient.GetContainerReference(containerName); | |
// Fetch info about files in the container | |
// Note: Loop with BlobContinuationToken to fetch results in pages. Pass null as currentToken to fetch all results. | |
BlobResultSegment resultSegment = await container.ListBlobsSegmentedAsync(currentToken: null); | |
IEnumerable<IListBlobItem> blobItems = resultSegment.Results; | |
// Extract the URI of the files into a new list | |
List<string> fileUris = new List<string>(); | |
foreach (var blobItem in blobItems) | |
{ | |
fileUris.Add(blobItem.StorageUri.PrimaryUri.ToString()); | |
} | |
return fileUris; | |
} | |
catch (System.Exception e) | |
{ | |
// Note: When using ASP.NET Core Web Apps, to output to streaming logs, use ILogger rather than System.Diagnostics | |
logger.LogError($"Exception occurred while attempting to list files on server: {e.Message}"); | |
return null; // or throw e; if you want to bubble the exception up to the caller | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment