Get started with Azure Files using F#

Azure Files is a service that offers file shares in the cloud using the standard Server Message Block (SMB) protocol. Both SMB 2.1 and SMB 3.0 are supported. With Azure Files, you can migrate legacy applications that rely on file shares to Azure quickly and without costly rewrites. Applications running in Azure virtual machines or cloud services or from on-premises clients can mount a file share in the cloud, just as a desktop application mounts a typical SMB share. Any number of application components can then mount and access the file storage share simultaneously.

For a conceptual overview of file storage, see the .NET guide for file storage.

Prerequisites

To use this guide, you must first create an Azure storage account. You'll also need your storage access key for this account.

Create an F# script and start F# interactive

The samples in this article can be used in either an F# application or an F# script. To create an F# script, create a file with the .fsx extension, for example files.fsx, in your F# development environment.

How to execute scripts

F# Interactive, dotnet fsi, can be launched interactively, or it can be launched from the command line to run a script. The command-line syntax is

> dotnet fsi [options] [ script-file [arguments] ]

Add packages in a script

Use #r nuget:package name to install the Azure.Storage.Blobs and Azure.Storage.Common and Azure.Storage.Files packages and open namespaces. Such as

> #r "nuget: Azure.Storage.Blobs"
> #r "nuget: Azure.Storage.Common"
> #r "nuget: Azure.Storage.Files"
open Azure.Storage.Blobs
open Azure.Storage.Sas
open Azure.Storage.Files
open Azure.Storage.Files.Shares
open Azure.Storage.Files.Shares.Models

Add namespace declarations

Add the following open statements to the top of the files.fsx file:

open System
open System.IO
open Azure
open Azure.Storage // Namespace for StorageSharedKeyCredential
open Azure.Storage.Blobs // Namespace for BlobContainerClient
open Azure.Storage.Sas // Namespace for ShareSasBuilder
open Azure.Storage.Files.Shares // Namespace for File storage types
open Azure.Storage.Files.Shares.Models // Namespace for ShareServiceProperties

Get your connection string

You'll need an Azure Storage connection string for this tutorial. For more information about connection strings, see Configure Storage Connection Strings.

For the tutorial, you'll enter your connection string in your script, like this:

let storageConnString = "..." // fill this in from your storage account

Create the file service client

The ShareClient type enables you to programmatically use files stored in File storage. Here's one way to create the service client:

let share = ShareClient(storageConnString, "shareName")

Now you are ready to write code that reads data from and writes data to File storage.

Create a file share

This example shows how to create a file share if it does not already exist:

share.CreateIfNotExistsAsync()

Create a directory

Here, you get the directory. You create if it doesn't already exist.

// Get a reference to the directory
let directory = share.GetDirectoryClient("directoryName")

// Create the directory if it doesn't already exist
directory.CreateIfNotExistsAsync()

Upload a file to the sample directory

This example shows how to upload a file to the sample directory.

let file = directory.GetFileClient("fileName")

let writeToFile localFilePath =
    use stream = File.OpenRead(localFilePath)
    file.Create(stream.Length)
    file.UploadRange(
        HttpRange(0L, stream.Length),
        stream)

writeToFile "localFilePath"

Download a file to a local file

Here you download the file just created, appending the contents to a local file.

let download = file.Download()

let copyTo saveDownloadPath =
    use downStream = File.OpenWrite(saveDownloadPath)
    download.Value.Content.CopyTo(downStream)

copyTo "Save_Download_Path"

Set the maximum size for a file share

The example below shows how to check the current usage for a share and how to set the quota for the share.

// stats.Usage is current usage in GB
let ONE_GIBIBYTE = 10_737_420_000L // Number of bytes in 1 gibibyte
let stats = share.GetStatistics().Value
let currentGiB = int (stats.ShareUsageInBytes / ONE_GIBIBYTE)

// Set the quota to 10 GB plus current usage
share.SetQuotaAsync(currentGiB + 10)

// Remove the quota
share.SetQuotaAsync(0)

Generate a shared access signature for a file or file share

You can generate a shared access signature (SAS) for a file share or for an individual file. You can also create a shared access policy on a file share to manage shared access signatures. Creating a shared access permissions is recommended, as it provides a means of revoking the SAS if it should be compromised.

Here, you create a shared access permissions on a share, and then set that permissions to provide the constraints for a SAS on a file in the share.

let accountName = "..." // Input your storage account name
let accountKey = "..." // Input your storage account key

// Create a 24-hour read/write policy.
let expiration = DateTimeOffset.UtcNow.AddHours(24.)
let fileSAS = ShareSasBuilder(
      ShareName = "shareName",
      FilePath = "filePath",
      Resource = "f",
      ExpiresOn = expiration)

// Set the permissions for the SAS
let permissions = ShareFileSasPermissions.All
fileSAS.SetPermissions(permissions)

// Create a SharedKeyCredential that we can use to sign the SAS token
let credential = StorageSharedKeyCredential(accountName, accountKey)

// Build a SAS URI
let fileSasUri = UriBuilder($"https://{accountName}.file.core.windows.net/{fileSAS.ShareName}/{fileSAS.FilePath}")
fileSasUri.Query = fileSAS.ToSasQueryParameters(credential).ToString()

For more information about creating and using shared access signatures, see Using Shared Access Signatures (SAS) and Create and use a SAS with Blob storage.

Copy files

You can copy a file to another file or to a blob, or a blob to a file. If you are copying a blob to a file, or a file to a blob, you must use a shared access signature (SAS) to authenticate the source object, even if you are copying within the same storage account.

Copy a file to another file

Here, you copy a file to another file in the same share. Because this copy operation copies between files in the same storage account, you can use Shared Key authentication to perform the copy.

let sourceFile = ShareFileClient(storageConnString, "shareName", "sourceFilePath")
let destFile = ShareFileClient(storageConnString, "shareName", "destFilePath")
destFile.StartCopyAsync(sourceFile.Uri)

Copy a file to a blob

Here, you create a file and copy it to a blob within the same storage account. You create a SAS for the source file, which the service uses to authenticate access to the source file during the copy operation.

// Create a new file SAS
let fileSASCopyToBlob = ShareSasBuilder(
    ShareName = "shareName",
    FilePath = "sourceFilePath",
    Resource = "f",
    ExpiresOn = DateTimeOffset.UtcNow.AddHours(24.))
let permissionsCopyToBlob = ShareFileSasPermissions.Read
fileSASCopyToBlob.SetPermissions(permissionsCopyToBlob)
let fileSasUriCopyToBlob = UriBuilder($"https://{accountName}.file.core.windows.net/{fileSASCopyToBlob.ShareName}/{fileSASCopyToBlob.FilePath}")

// Get a reference to the file.
let sourceFileCopyToBlob = ShareFileClient(fileSasUriCopyToBlob.Uri)

// Get a reference to the blob to which the file will be copied.
let containerCopyToBlob = BlobContainerClient(storageConnString, "containerName");
containerCopyToBlob.CreateIfNotExists()
let destBlob = containerCopyToBlob.GetBlobClient("blobName")
destBlob.StartCopyFromUriAsync(sourceFileCopyToBlob.Uri)

You can copy a blob to a file in the same way. If the source object is a blob, then create a SAS to authenticate access to that blob during the copy operation.

Troubleshooting File storage using metrics

Azure Storage Analytics supports metrics for File storage. With metrics data, you can trace requests and diagnose issues.

You can enable metrics for File storage from the Azure portal, or you can do it from F# like this:

// Instantiate a ShareServiceClient
let shareService = ShareServiceClient(storageConnString);

// Set metrics properties for File service
let props = ShareServiceProperties()

props.HourMetrics = ShareMetrics(
    Enabled = true,
    IncludeApis = true,
    Version = "1.0",
    RetentionPolicy = ShareRetentionPolicy(Enabled = true,Days = 14))

props.MinuteMetrics = ShareMetrics(
    Enabled = true,
    IncludeApis = true,
    Version = "1.0",
    RetentionPolicy = ShareRetentionPolicy(Enabled = true,Days = 7))

shareService.SetPropertiesAsync(props)

Next steps

For more information about Azure Files, see these links.

Conceptual articles and videos

Tooling support for File storage

Reference

Blog posts