使用 .NET 第 11.x 版用戶端程式庫的 Azure 檔案共用程式代碼範例

本文說明使用適用於 .NET 的 Azure 檔案共用用戶端程式庫第 11.x 版的程式碼範例。

在 2023 年 3 月 31 日,我們已淘汰對不符合目前 Azure SDK 指導方針的 Azure SDK 程式庫支援。 新的 Azure SDK 程式庫會定期更新,以促進一致的體驗並加強您的安全性態勢。 建議您轉換至新的 Azure SDK 程式庫,以利用新功能和重大安全性更新。

雖然較舊的程式庫仍可在 2023 年 3 月 31 日之後使用,但它們將不再收到 Microsoft 的官方支援和更新。 如需詳細資訊,請參閱支援淘汰公告

必要條件

在專案目錄中安裝這些套件:

  • Microsoft.Azure.Storage.Common
  • Microsoft.Azure.Storage.File
  • Microsoft.Azure.ConfigurationManager

新增下列 using 指示詞:

using Microsoft.Azure;              // Namespace for Azure Configuration Manager
using Microsoft.Azure.Storage;      // Namespace for Storage Client Library
using Microsoft.Azure.Storage.Blob; // Namespace for Azure Blobs
using Microsoft.Azure.Storage.File; // Namespace for Azure Files

存取檔案共用

相關文章:使用 .NET 開發 Azure 檔案儲存體

新增下列程式代碼以存取檔案共用:

// Create a CloudFileClient object for credentialed access to Azure Files.
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

// Get a reference to the file share we created previously.
CloudFileShare share = fileClient.GetShareReference("logs");

// Ensure that the share exists.
if (share.Exists())
{
    // Get a reference to the root directory for the share.
    CloudFileDirectory rootDir = share.GetRootDirectoryReference();

    // Get a reference to the directory we created previously.
    CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("CustomLogs");

    // Ensure that the directory exists.
    if (sampleDir.Exists())
    {
        // Get a reference to the file we created previously.
        CloudFile file = sampleDir.GetFileReference("Log1.txt");

        // Ensure that the file exists.
        if (file.Exists())
        {
            // Write the contents of the file to the console window.
            Console.WriteLine(file.DownloadTextAsync().Result);
        }
    }
}

設定檔案共用的大小上限

相關文章:使用 .NET 開發 Azure 檔案儲存體

從 Azure 檔案儲存體用戶端程式庫 5.x 版開始,您可以設定檔案共用配額 (或大小上限)。 您也可以檢查有多少資料目前儲存在共用上。

設定共用的配額會限制儲存在共用上的檔案大小總計。 如果共用上的檔案大小總計超過配額,用戶端就無法增加現有檔案的大小。 用戶端也無法建立新檔案,除非這些檔案是空的。

下列範例示範如何檢查共用的目前使用狀況,以及如何設定共用的配額。

// Parse the connection string for the storage account.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    Microsoft.Azure.CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create a CloudFileClient object for credentialed access to Azure Files.
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

// Get a reference to the file share we created previously.
CloudFileShare share = fileClient.GetShareReference("logs");

// Ensure that the share exists.
if (share.Exists())
{
    // Check current usage stats for the share.
    // Note that the ShareStats object is part of the protocol layer for the File service.
    Microsoft.Azure.Storage.File.Protocol.ShareStats stats = share.GetStats();
    Console.WriteLine("Current share usage: {0} GiB", stats.Usage.ToString());

    // Specify the maximum size of the share, in GiB.
    // This line sets the quota to be 10 GiB greater than the current usage of the share.
    share.Properties.Quota = 10 + stats.Usage;
    share.SetProperties();

    // Now check the quota for the share. Call FetchAttributes() to populate the share's properties.
    share.FetchAttributes();
    Console.WriteLine("Current share quota: {0} GiB", share.Properties.Quota);
}

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

從 Azure 檔案儲存體用戶端程式庫 5.x 版開始,您可以產生檔案共用或個別檔案的共用存取簽章 (SAS)。

您也可以在檔案共用上建立預存存取原則,以管理共用存取簽章。 建議您建立預存存取原則,因為可讓您在 SAS 遭到入侵時予以撤銷。 下列範例會在共用上建立預存存取原則。 此範例會使用該原則對共用中檔案的 SAS 提供條件約束。

// Parse the connection string for the storage account.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    Microsoft.Azure.CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create a CloudFileClient object for credentialed access to Azure Files.
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

// Get a reference to the file share we created previously.
CloudFileShare share = fileClient.GetShareReference("logs");

// Ensure that the share exists.
if (share.Exists())
{
    string policyName = "sampleSharePolicy" + DateTime.UtcNow.Ticks;

    // Create a new stored access policy and define its constraints.
    SharedAccessFilePolicy sharedPolicy = new SharedAccessFilePolicy()
        {
            SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
            Permissions = SharedAccessFilePermissions.Read | SharedAccessFilePermissions.Write
        };

    // Get existing permissions for the share.
    FileSharePermissions permissions = share.GetPermissions();

    // Add the stored access policy to the share's policies. Note that each policy must have a unique name.
    permissions.SharedAccessPolicies.Add(policyName, sharedPolicy);
    share.SetPermissions(permissions);

    // Generate a SAS for a file in the share and associate this access policy with it.
    CloudFileDirectory rootDir = share.GetRootDirectoryReference();
    CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("CustomLogs");
    CloudFile file = sampleDir.GetFileReference("Log1.txt");
    string sasToken = file.GetSharedAccessSignature(null, policyName);
    Uri fileSasUri = new Uri(file.StorageUri.PrimaryUri.ToString() + sasToken);

    // Create a new CloudFile object from the SAS, and write some text to the file.
    CloudFile fileSas = new CloudFile(fileSasUri);
    fileSas.UploadText("This write operation is authorized via SAS.");
    Console.WriteLine(fileSas.DownloadText());
}

複製檔案

相關文章:使用 .NET 開發 Azure 檔案儲存體

從 Azure 檔案儲存體用戶端程式庫 5.x 版開始,您可以將檔案複製到另一個檔案、將檔案複製到 Blob 或將 Blob 複製到檔案。

您也可以使用 AzCopy 將檔案複製到另一個檔案,或將 Blob 複製到檔案或反向操作。 請參閱開始使用 AzCopy

注意

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

將檔案複製到另一個檔案

下列範例會將檔案複製到相同共用中的另一個檔案。 您可以使用共用金鑰驗證來執行複製作業,因為這項作業會複製相同儲存體帳戶內的檔案。

// Parse the connection string for the storage account.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    Microsoft.Azure.CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create a CloudFileClient object for credentialed access to Azure Files.
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

// Get a reference to the file share we created previously.
CloudFileShare share = fileClient.GetShareReference("logs");

// Ensure that the share exists.
if (share.Exists())
{
    // Get a reference to the root directory for the share.
    CloudFileDirectory rootDir = share.GetRootDirectoryReference();

    // Get a reference to the directory we created previously.
    CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("CustomLogs");

    // Ensure that the directory exists.
    if (sampleDir.Exists())
    {
        // Get a reference to the file we created previously.
        CloudFile sourceFile = sampleDir.GetFileReference("Log1.txt");

        // Ensure that the source file exists.
        if (sourceFile.Exists())
        {
            // Get a reference to the destination file.
            CloudFile destFile = sampleDir.GetFileReference("Log1Copy.txt");

            // Start the copy operation.
            destFile.StartCopy(sourceFile);

            // Write the contents of the destination file to the console window.
            Console.WriteLine(destFile.DownloadText());
        }
    }
}

將檔案複製到 Blob

下列範例會建立檔案,並將其複製到相同儲存體帳戶內的 Blob。 此範例會建立來源檔案的 SAS,供服務用來在複製作業期間授權來源檔案存取權。

// Parse the connection string for the storage account.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    Microsoft.Azure.CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create a CloudFileClient object for credentialed access to Azure Files.
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

// Create a new file share, if it does not already exist.
CloudFileShare share = fileClient.GetShareReference("sample-share");
share.CreateIfNotExists();

// Create a new file in the root directory.
CloudFile sourceFile = share.GetRootDirectoryReference().GetFileReference("sample-file.txt");
sourceFile.UploadText("A sample file in the root directory.");

// Get a reference to the blob to which the file will be copied.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("sample-container");
container.CreateIfNotExists();
CloudBlockBlob destBlob = container.GetBlockBlobReference("sample-blob.txt");

// Create a SAS for the file that's valid for 24 hours.
// Note that when you are copying a file to a blob, or a blob to a file, you must use a SAS
// to authorize access to the source object, even if you are copying within the same
// storage account.
string fileSas = sourceFile.GetSharedAccessSignature(new SharedAccessFilePolicy()
{
    // Only read permissions are required for the source file.
    Permissions = SharedAccessFilePermissions.Read,
    SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24)
});

// Construct the URI to the source file, including the SAS token.
Uri fileSasUri = new Uri(sourceFile.StorageUri.PrimaryUri.ToString() + fileSas);

// Copy the file to the blob.
destBlob.StartCopy(fileSasUri);

// Write the contents of the file to the console window.
Console.WriteLine("Source file contents: {0}", sourceFile.DownloadText());
Console.WriteLine("Destination blob contents: {0}", destBlob.DownloadText());

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

共用快照集

相關文章:使用 .NET 開發 Azure 檔案儲存體

從 Azure 檔案儲存體用戶端程式庫的 8.5 版開始,您可以建立共用快照集。 您也可以列出或瀏覽共用快照集,並將共用快照集刪除。 一旦建立,共用快照集就會是唯讀的。

建立共用快照集

下列範例會建立檔案共用快照集:

storageAccount = CloudStorageAccount.Parse(ConnectionString); 
fClient = storageAccount.CreateCloudFileClient(); 
string baseShareName = "myazurefileshare"; 
CloudFileShare myShare = fClient.GetShareReference(baseShareName); 
var snapshotShare = myShare.Snapshot();

列出共用快照集

下列範例會列出共用上的快照集:

var shares = fClient.ListShares(baseShareName, ShareListingDetails.All);

列出共用快照集內的檔案和目錄

下列範例會瀏覽共用快照集內的檔案和目錄:

CloudFileShare mySnapshot = fClient.GetShareReference(baseShareName, snapshotTime); 
var rootDirectory = mySnapshot.GetRootDirectoryReference(); 
var items = rootDirectory.ListFilesAndDirectories();

從共用快照集還原檔案共用或檔案

擷取檔案共用的快照集可讓您將個別檔案或整個檔案共用復原。

您可以從檔案共用快照集還原檔案,方法是查詢檔案共用的共用快照集。 然後,您可以擷取屬於特定共用快照集的檔案。 您可以使用該版本直接讀取或還原檔案。

CloudFileShare liveShare = fClient.GetShareReference(baseShareName);
var rootDirOfliveShare = liveShare.GetRootDirectoryReference();
var dirInliveShare = rootDirOfliveShare.GetDirectoryReference(dirName);
var fileInliveShare = dirInliveShare.GetFileReference(fileName);

CloudFileShare snapshot = fClient.GetShareReference(baseShareName, snapshotTime);
var rootDirOfSnapshot = snapshot.GetRootDirectoryReference();
var dirInSnapshot = rootDirOfSnapshot.GetDirectoryReference(dirName);
var fileInSnapshot = dir1InSnapshot.GetFileReference(fileName);

string sasContainerToken = string.Empty;
SharedAccessFilePolicy sasConstraints = new SharedAccessFilePolicy();
sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24);
sasConstraints.Permissions = SharedAccessFilePermissions.Read;

//Generate the shared access signature on the container, setting the constraints directly on the signature.
sasContainerToken = fileInSnapshot.GetSharedAccessSignature(sasConstraints);

string sourceUri = (fileInSnapshot.Uri.ToString() + sasContainerToken + "&" + fileInSnapshot.SnapshotTime.ToString()); ;
fileInliveShare.StartCopyAsync(new Uri(sourceUri));

刪除共用快照集

下列範例會刪除檔案共用快照集:

CloudFileShare mySnapshot = fClient.GetShareReference(baseShareName, snapshotTime); mySnapshot.Delete(null, null, null);

使用計量針對 Azure 檔案儲存體進行疑難排解

相關文章:使用 .NET 開發 Azure 檔案儲存體

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

您可以透過 Azure 入口網站啟用 Azure 檔案儲存體的計量。 您也可以透過 REST API 或 Azure 檔案儲存體用戶端程式庫中的其中一個同類工具來呼叫設定檔案服務屬性作業,以程式設計方式啟用計量。

下列程式碼範例會示範如何使用 .NET 用戶端程式庫,啟用 Azure 檔案儲存體的計量。

首先,將下列 using 指示詞新增至您的 Program.cs 檔案,還有您在上面新增的項目:

using Microsoft.Azure.Storage.File.Protocol;
using Microsoft.Azure.Storage.Shared.Protocol;

雖然 Azure Blob、Azure 資料表以及 Azure 佇列會在 Microsoft.Azure.Storage.Shared.Protocol 命名空間中使用共用的 ServiceProperties 類型,但 Azure 檔案儲存體會使用自己的類型,在 Microsoft.Azure.Storage.File.Protocol 命名空間中的 FileServiceProperties 類型。 不過,這兩個命名空間都必須從您的程式碼加以參考,以供下列程式碼進行編譯。

// Parse your storage connection string from your application's configuration file.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
        Microsoft.Azure.CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the File service client.
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();

// Set metrics properties for File service.
// Note that the File service currently uses its own service properties type,
// available in the Microsoft.Azure.Storage.File.Protocol namespace.
fileClient.SetServiceProperties(new FileServiceProperties()
{
    // Set hour metrics
    HourMetrics = new MetricsProperties()
    {
        MetricsLevel = MetricsLevel.ServiceAndApi,
        RetentionDays = 14,
        Version = "1.0"
    },
    // Set minute metrics
    MinuteMetrics = new MetricsProperties()
    {
        MetricsLevel = MetricsLevel.ServiceAndApi,
        RetentionDays = 7,
        Version = "1.0"
    }
});

// Read the metrics properties we just set.
FileServiceProperties serviceProperties = fileClient.GetServiceProperties();
Console.WriteLine("Hour metrics:");
Console.WriteLine(serviceProperties.HourMetrics.MetricsLevel);
Console.WriteLine(serviceProperties.HourMetrics.RetentionDays);
Console.WriteLine(serviceProperties.HourMetrics.Version);
Console.WriteLine();
Console.WriteLine("Minute metrics:");
Console.WriteLine(serviceProperties.MinuteMetrics.MetricsLevel);
Console.WriteLine(serviceProperties.MinuteMetrics.RetentionDays);
Console.WriteLine(serviceProperties.MinuteMetrics.Version);