使用 F# 開始使用 Azure 檔案儲存體

Azure 檔案儲存體是使用標準伺服器訊息區塊 (SMB) 通訊協定,以在雲端中提供檔案共用功能的服務。 SMB 2.1 和 SMB 3.0 皆受到支援。 使用 Azure 檔案儲存體時,您可以將依賴檔案共用功能的舊式應用程式快速移轉至 Azure,而且不必浪費成本重新撰寫程式。 在 Azure 虛擬機器或雲端服務或從內部部署用戶端中執行的應用程式可以在雲端中掛接檔案共用,就像傳統型應用程式掛接一般 SMB 共用一樣。 可供任何數量的應用程式元件同時掛接和存取檔案儲存體共用。

如需檔案儲存體的概念性概觀,請參閱檔案儲存體的 .NET 指南

必要條件

若要使用本指南,您必須先建立 Azure 儲存體帳戶。 您也需要擁有此帳戶的儲存體存取金鑰。

建立 F# 指令碼並啟動 F# 互動

本文中的範例可用於 F# 應用程式或 F# 指令碼。 若要建立 F# 指令碼,請在 F# 開發環境中建立副檔名為 .fsx 的檔案,例如 files.fsx

如何執行指令碼

F# 互動 dotnet fsi 可透過互動方式啟動,也可從命令列中啟動以執行指令碼。 命令列語法為

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

在指令碼中新增封裝

使用 #rnuget:package name 來安裝 Azure.Storage.BlobsAzure.Storage.CommonAzure.Storage.Files 封裝和 open 命名空間。 例如

> #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

新增命名空間宣告

files.fsx 檔案最上方加入下列 open 陳述式:

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

取得您的連接字串

在本教學課程中,您將需要 Azure 儲存體連接字串。 如需連接字串的詳細資訊,請參閱設定儲存體連接字串

在本教學課程中,您將在指令碼中輸入連接字串,如下所示:

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

建立檔案服務用戶端

ShareClient 型別可供您透過程式設計方式使用儲存在檔案儲存體中的檔案。 以下為建立服務用戶端的一種方式:

let share = ShareClient(storageConnString, "shareName")

現在,您可以開始寫入程式碼,以讀取檔案儲存體的資料並將資料寫入其中。

建立檔案共用

此範例說明如何建立尚不存在的檔案共用:

share.CreateIfNotExistsAsync()

建立目錄

在這裡,您會取得目錄。 如果目錄不存在,請建立。

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

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

將檔案上傳至樣本目錄

此範例說明如何將檔案上傳至樣本目錄。

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"

將檔案下載至本機檔案

在這裡,您會下載剛建立的檔案,並將內容附加至本機檔案。

let download = file.Download()

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

copyTo "Save_Download_Path"

設定檔案共用的大小上限

下列範例說明如何檢查共用的目前使用量,以及如何設定共用的配額。

// 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)

產生檔案或檔案共用的共用存取簽章

您可以為檔案共用或個別檔案產生共用存取簽章 (SAS)。 您也可以在檔案共用上建立共用存取原則,以管理共用存取簽章。 建議您建立共用存取權限,因為如果 SAS 遭到入侵,其可提供一種撤銷 SAS 的方式。

在這裡,您會在共用上建立共用存取權限,然後設定該權限以為在共用檔案上的 SAS 提供限制式。

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()

如需建立和使用共用存取簽章的詳細資訊,請參閱使用共用存取簽章 (SAS) 以及搭配 Blob 儲存體建立和使用 SAS

複製檔案

您可將檔案複製到另一個檔案或 blob,或將 blob 複製到檔案。 如果您要將 blob 複製到檔案,或將檔案複製到 blob,則必須使用共用存取簽章 (SAS) 驗證來源物件,即使是在相同的儲存體帳戶內進行複製也一樣。

將檔案複製到另一個檔案

在這裡,您會將檔案複製到相同共用中的另一個檔案。 由於此複製作業會在相同儲存體帳戶的檔案之間複製,因此您可以使用共用金鑰驗證來執行該複製。

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

將檔案複製到 Blob

在這裡,您會建立檔案,並將其複製到同一個儲存體帳戶內的 Blob。 您會建立來源檔案的 SAS,供服務用來在複製作業的過程中驗證存取來源檔案。

// 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)

您可以使用相同方式將 Blob 複製到檔案。 如果來源物件是 Blob,則建立 SAS 以在複製作業期間驗證該 Blob 的存取權。

使用計量疑難排解檔案儲存體

Azure 儲存體分析支援檔案儲存體的計量。 透過計量資料,您可以追蹤要求並診斷問題。

您可從 Azure 入口網站啟用檔案儲存體的計量,或從 F# 執行此動作,如下所示:

// 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)

下一步

如需 Azure 檔案儲存體的詳細資訊,請參閱下列連結。

概念性文章和影片

支援檔案儲存體工具

參考

部落格文章