United Kingdom: +44 (0)208 088 8978

Azure Blobs with F#

Akash uses FSI to explore Azure Blob Storage

We're hiring Software Developers

Click here to find out more

Recently I've been learning a lot about F# and Azure. One thing I've started doing is using F# scripts as a playground to quickly learn how to interact with Azure services. It's an easy way to explore new tools without any noise, so let's start by creating Blob.fsx!

Import in the packages we'll need in order to play around with blob storage:

#r "nuget: Azure.Storage.Blobs"
#r "nuget: TaskBuilder.fs" // only required if you want to use the async methods

open Azure.Storage.Blobs
open FSharp.Control.Tasks.V2

Now we'll need to create an instance of a BlobServiceClient. This will allow us to manipulate blob containers.

let connectionString = "<connection_string>"
let blobServiceClient = BlobServiceClient connectionString

Here's a guide on how to get the connection string from your storage account on Azure.

With that we'll have access to methods on the service client to create a container which will hold our blobs.

let images = "images"

let createImagesBlobContainer = task {
    let! response = blobServiceClient.CreateBlobContainerAsync images
    return response.Value

Above we've defined a value that will create a BlobContainerClient with the name images, we're using the task computation expression to handle the async method - there is also a sync method that can be used.

A BlobContainerClient will let you manipulate Azure Storage containers and their blobs.
We can also use the below snippet to directly access the images BlobContainerClient.

let imagesBlobContainer = blobServiceClient.GetBlobContainerClient images

Time to add images to our images container!

let displayPic = "display-pic"
let imageFilePath = """C:\Users\Akash\Pictures\cit-logo.png"""

let fileStream = File.OpenRead imageFilePath

let uploadDisplayPic = task {
    let! response = imagesBlobContainer.UploadBlobAsync(displayPic, fileStream)
    return response.Value

Now we have something in our container we can retrieve it using

let getDisplayPictureBlob = imagesBlobContainer.GetBlobClient(displayPic)

But if we want to access multiple items in our BlobContainer we can do:

let blobNames =
    let blobItems = imagesBlobContainer.GetBlobs()
    [ for blobItem in blobItems do blobItem.Name ]

// val blobNames : string list = ["display-pic"]

With just a few code snippets we're able to read and write to blob storage. There are a tonne more things you can do with blobs and FSX files are the perfect lightweight environment to get going.