Skip to content

Instantly share code, notes, and snippets.

@dazfuller
Last active March 30, 2021 16:22
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dazfuller/9b5ea145525879fb5114bd78b53e9ee5 to your computer and use it in GitHub Desktop.
Save dazfuller/9b5ea145525879fb5114bd78b53e9ee5 to your computer and use it in GitHub Desktop.
Download files from Azure Blob Storage using a SAS token
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
namespace AzureBlobStorage
{
internal static class Program
{
private static void Main()
{
const string accountName = "account-name";
const string blobContainerName = "blob-container-name";
const string downloadLocation = @"C:\data";
const string sasToken =
@"<SAS token (just the token, not the URI)>";
// Create a credential object from the SAS token then use this and the account name to create a cloud storage connection
var accountSAS = new StorageCredentials(sasToken);
var storageAccount = new CloudStorageAccount(accountSAS, accountName, null, true);
// Get the Blob storage container
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference(blobContainerName);
// Fail if the container does not exist
if (!container.Exists())
{
Console.Error.WriteLine($"Can't find container '{blobContainerName}'");
return;
}
// Get the list of blobs in the container, just for demo purposes this is ordered by blob name and taking only
// the first 10 items
var blobs = container
.ListBlobs(blobListingDetails: BlobListingDetails.Metadata)
.OfType<CloudBlob>()
.OrderBy(blobItem => blobItem.Name)
.Take(10)
.ToList();
// Set the request options to ensure we're performing MD5 validation
var downloadOptions = new BlobRequestOptions
{
DisableContentMD5Validation = false,
UseTransactionalMD5 = true
};
// Download the files
// The parameters are named for reference only and can safely be removed
Task.WaitAll(
blobs.Select(
blobItem => blobItem.DownloadToFileAsync(
path: Path.Combine(downloadLocation, blobItem.Name),
mode: FileMode.Create,
accessCondition: null,
options: downloadOptions,
operationContext: null)).ToArray());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment