Setting up Connection to Storage Account Blob
Introduction
If you are building an Azure Function, you can use Function Bindings to push data into Azure Storage.
This solution can be used for any C# project, including Azure Functions.
Required Packages
Install these via NuGet.
Azure.Storage.Blobs
Azure.Identity
Code Block
Using Statements
# Using Statements
using Azure.Identity;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs.Specialized; // You may not need this one
# Namespace and class setup removed for brevity
# The below goes inside your method
# Convert base64 to Memory Stream
string base64Content = "<some base64 string here>";
byte[] content = Convert.FromBase64String(base64Content);
MemoryStream ms = new MemoryStream(content);
# Storage Blob Connection
string storageAccountName = "<your storage account name here>";
string blobName = "<blob name here>";
BlobServiceClient serviceClient = new(
new Uri($"https://{storageAccountName}.blob.core.windows.net"),
new DefaultAzureCredential()
);
BlobContainerClient blobContainerClient;
blobContainerClient = serviceClient.GetBlobContainerClient("checklistuploads");
await blobContainerClient.CreateIfNotExistsAsync(
PublicAccessType.None, null, null, cancellationToken
);
BlobClient blobClient = blobContainerClient.GetBlobClient(fullPath);
await blobClient.UploadAsync(contents, true, cancellationToken);Final Comments
There are improvements here, such as converting this into the appropriate set of Classes to be used in Dependency Injection, so you don't need to setup a connection in multiple methods.
This use case only had a single method that needed it, so it was elected not to setup Dependency Injection yet.
Last updated