使用 .NET 開發 Azure 檔案服務Develop for Azure Files with .NET

瞭解開發使用 Azure 檔案儲存體 儲存資料之 .net 應用程式的基本概念。Learn the basics of developing .NET applications that use Azure Files to store data. 本文說明如何建立簡單的主控台應用程式,以使用 .NET 和 Azure 檔案儲存體來執行下列作業:This article shows how to create a simple console application to do the following with .NET and Azure Files:

  • 取得檔案的內容。Get the contents of a file.
  • 設定檔案共用的大小上限或配額。Set the maximum size, or quota, for a file share.
  • 建立檔案 (SAS) 的共用存取簽章。Create a shared access signature (SAS) for a file.
  • 將檔案複製到相同儲存體帳戶中的另一個檔案。Copy a file to another file in the same storage account.
  • 將檔案複製到相同儲存體帳戶中的 Blob。Copy a file to a blob in the same storage account.
  • 建立檔案共用的快照集。Create a snapshot of a file share.
  • 從共用快照集還原檔案。Restore a file from a share snapshot.
  • 使用 Azure 儲存體計量來進行疑難排解。Use Azure Storage Metrics for troubleshooting.

若要深入瞭解 Azure 檔案儲存體,請參閱 Azure 檔案儲存體是什麼?To learn more about Azure Files, see What is Azure Files?

提示

請查看 Azure 儲存體程式碼範例儲存機制Check out the Azure Storage code samples repository

如需可供您下載和執行的簡易端對端 Azure 儲存體程式碼範例,請查看我們的 Azure 儲存體範例清單。For easy-to-use end-to-end Azure Storage code samples that you can download and run, please check out our list of Azure Storage Samples.

了解 .NET APIUnderstanding the .NET APIs

Azure 檔案服務會提供兩種廣泛的方法給用戶端應用程式:伺服器訊息區 (SMB) 和 REST。Azure Files provides two broad approaches to client applications: Server Message Block (SMB) and REST. 在 .NET 中, System.IOAzure.Storage.Files.Shares api 會將這些方法抽象化。Within .NET, the System.IO and Azure.Storage.Files.Shares APIs abstract these approaches.

APIAPI 使用時機When to use 注意Notes
System.IOSystem.IO 您的應用程式:Your application:
  • 需要使用 SMB 讀取/寫入檔案Needs to read/write files by using SMB
  • 正在可透過連接埠 445 存取您 Azure 檔案服務帳戶的裝置上執行Is running on a device that has access over port 445 to your Azure Files account
  • 不需要管理檔案共用的任何系統管理設定Doesn't need to manage any of the administrative settings of the file share
使用 Azure 檔案儲存體 over SMB 執行的檔案 i/o 通常與任何網路檔案共用或本機存放裝置的 i/o 相同。File I/O implemented with Azure Files over SMB is generally the same as I/O with any network file share or local storage device. 如需 .NET 中許多功能的簡介,包括檔案 i/o,請參閱 主控台應用程式 教學課程。For an introduction to a number of features in .NET, including file I/O, see the Console Application tutorial.
Azure。共用Azure.Storage.Files.Shares 您的應用程式:Your application:
  • 因為防火牆或 ISP 條件約束,所以無法在埠445上使用 SMB 存取 Azure 檔案儲存體Can't access Azure Files by using SMB on port 445 because of firewall or ISP constraints
  • 需要系統管理功能,例如設定檔案共用的配額,或建立共用存取簽章的能力Requires administrative functionality, such as the ability to set a file share's quota or create a shared access signature
本文將示範如何使用 Azure.Storage.Files.Shares REST 而非 SMB 和檔案共用的管理來使用檔案 i/o。This article demonstrates the use of Azure.Storage.Files.Shares for file I/O using REST instead of SMB and management of the file share.

建立主控台應用程式並取得組件Create the console application and obtain the assembly

您可以在任何類型的 .NET 應用程式中使用 Azure 檔案儲存體用戶端程式庫。You can use the Azure Files client library in any type of .NET app. 這些應用程式包括 Azure 雲端、web、桌面和行動應用程式。These apps include Azure cloud, web, desktop, and mobile apps. 在本指南中,我們會建立簡單的主控台應用程式。In this guide, we create a console application for simplicity.

在 Visual Studio 中,建立新的 Windows 主控台應用程式。In Visual Studio, create a new Windows console application. 下列步驟說明如何在 Visual Studio 2019 中建立主控台應用程式。The following steps show you how to create a console application in Visual Studio 2019. 這些步驟類似其他 Visual Studio 版本中的步驟。The steps are similar in other versions of Visual Studio.

  1. 啟動 Visual Studio,然後選取 [建立新專案]。Start Visual Studio and select Create a new project.
  2. 在 [ 建立新專案] 中,選擇 [ 主控台應用程式 (] .NET Framework) 的 c #,然後選取 [下一步]In Create a new project, choose Console App (.NET Framework) for C#, and then select Next.
  3. 在 [ 設定您的新專案] 中,輸入應用程式的名稱,然後選取 [ 建立]。In Configure your new project, enter a name for the app, and select Create.

將本文中的所有程式碼範例新增至 Program Program.cs 檔案中的類別。Add all the code examples in this article to the Program class in the Program.cs file.

使用 NuGet 來安裝必要的封裝Use NuGet to install the required packages

請在您的專案中參考這些套件:Refer to these packages in your project:

您可以使用 NuGet 來取得套件。You can use NuGet to obtain the packages. 請遵循下列步驟:Follow these steps:

  1. 方案總管 中,以滑鼠右鍵按一下您的專案,然後選擇 [ 管理 NuGet 套件]。In Solution Explorer, right-click your project and choose Manage NuGet Packages.

  2. 在 [NuGet 套件管理員] 中,選取 [瀏覽]。In NuGet Package Manager, select Browse. 然後搜尋並選擇 Azure Core,然後選取 [ 安裝]。Then search for and choose Azure.Core, and then select Install.

    此步驟會安裝封裝及其相依性。This step installs the package and its dependencies.

  3. 搜尋並安裝這些封裝:Search for and install these packages:

    • Azure. BlobAzure.Storage.Blobs
    • Azure。共用Azure.Storage.Files.Shares
    • System.Configuration.ConfigurationManagerSystem.Configuration.ConfigurationManager

將儲存體帳號憑證儲存至 App.config 檔案Save your storage account credentials to the App.config file

接下來,將您的認證儲存在專案的 App.config 檔案中。Next, save your credentials in your project's App.config file. 方案總管 中,按兩下 App.config 並編輯檔案,使其類似于下列範例。In Solution Explorer, double-click App.config and edit the file so that it is similar to the following example.

myaccount 以您的儲存體帳戶名稱取代,並 mykey 以您的儲存體帳戶金鑰取代。Replace myaccount with your storage account name and mykey with your storage account key.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="StorageConnectionString" 
      value="DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=mykey;EndpointSuffix=core.windows.net" />
    <add key="StorageAccountName" value="myaccount" />
    <add key="StorageAccountKey" value="mykey" />
  </appSettings>
</configuration>

注意

Azurite 儲存體模擬器目前不支援 Azure 檔案儲存體。 您的連接字串必須以雲端中的 Azure 儲存體帳戶為目標,才能與 Azure 檔案儲存體搭配運作。Your connection string must target an Azure storage account in the cloud to work with Azure Files.

新增 using 指示詞Add using directives

方案總管 中,開啟 Program.cs 檔案,並將下列 using 指示詞新增至檔案頂端。In Solution Explorer, open the Program.cs file, and add the following using directives to the top of the file.

using System;
using System.Configuration;
using System.IO;
using System.Threading.Tasks;
using Azure;
using Azure.Storage;
using Azure.Storage.Blobs;
using Azure.Storage.Files.Shares;
using Azure.Storage.Files.Shares.Models;
using Azure.Storage.Sas;

以程式設計方式存取檔案共用Access the file share programmatically

Program.cs 檔案中,新增下列程式碼以程式設計方式存取檔案共用。In the Program.cs file, add the following code to access the file share programmatically.

下列方法會建立檔案共用(如果尚未存在)。The following method creates a file share if it doesn't already exist. 方法會從連接字串建立 ShareClient 物件開始。The method starts by creating a ShareClient object from a connection string. 然後,此範例會嘗試下載我們稍早建立的檔案。The sample then attempts to download a file we created earlier. 從呼叫這個方法 Main()Call this method from Main().

//-------------------------------------------------
// Create a file share
//-------------------------------------------------
public async Task CreateShareAsync(string shareName)
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instantiate a ShareClient which will be used to create and manipulate the file share
    ShareClient share = new ShareClient(connectionString, shareName);

    // Create the share if it doesn't already exist
    await share.CreateIfNotExistsAsync();

    // Ensure that the share exists
    if (await share.ExistsAsync())
    {
        Console.WriteLine($"Share created: {share.Name}");

        // Get a reference to the sample directory
        ShareDirectoryClient directory = share.GetDirectoryClient("CustomLogs");

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

        // Ensure that the directory exists
        if (await directory.ExistsAsync())
        {
            // Get a reference to a file object
            ShareFileClient file = directory.GetFileClient("Log1.txt");

            // Ensure that the file exists
            if (await file.ExistsAsync())
            {
                Console.WriteLine($"File exists: {file.Name}");

                // Download the file
                ShareFileDownloadInfo download = await file.DownloadAsync();

                // Save the data to a local file, overwrite if the file already exists
                using (FileStream stream = File.OpenWrite(@"downloadedLog1.txt"))
                {
                    await download.Content.CopyToAsync(stream);
                    await stream.FlushAsync();
                    stream.Close();

                    // Display where the file was saved
                    Console.WriteLine($"File downloaded: {stream.Name}");
                }
            }
        }
    }
    else
    {
        Console.WriteLine($"CreateShareAsync failed");
    }
}

設定檔案共用的大小上限Set the maximum size for a file share

從 Azure 檔案儲存體用戶端程式庫5.x 版開始,您可以設定檔案共用的配額 (大小上限) 。Beginning with version 5.x of the Azure Files client library, you can set the quota (maximum size) for a file share. 您也可以檢查有多少資料目前儲存在共用上。You can also check to see how much data is currently stored on the share.

設定共用配額會限制儲存在共用上的檔案大小總計。Setting the quota for a share limits the total size of the files stored on the share. 如果共用上的檔案大小總計超過配額,用戶端就無法增加現有檔案的大小。If the total size of files on the share exceeds the quota, clients can't increase the size of existing files. 用戶端也無法建立新檔案,除非這些檔案是空的。Clients also can't create new files, unless those files are empty.

下列範例示範如何檢查共用的目前使用狀況,以及如何設定共用的配額。The example below shows how to check the current usage for a share and how to set the quota for the share.

//-------------------------------------------------
// Set the maximum size of a share
//-------------------------------------------------
public async Task SetMaxShareSizeAsync(string shareName, int increaseSizeInGiB)
{
    const long ONE_GIBIBYTE = 10737420000; // Number of bytes in 1 gibibyte

    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instantiate a ShareClient which will be used to access the file share
    ShareClient share = new ShareClient(connectionString, shareName);

    // Create the share if it doesn't already exist
    await share.CreateIfNotExistsAsync();

    // Ensure that the share exists
    if (await share.ExistsAsync())
    {
        // Get and display current share quota
        ShareProperties properties = await share.GetPropertiesAsync();
        Console.WriteLine($"Current share quota: {properties.QuotaInGB} GiB");

        // Get and display current usage stats for the share
        ShareStatistics stats = await share.GetStatisticsAsync();
        Console.WriteLine($"Current share usage: {stats.ShareUsageInBytes} bytes");

        // Convert current usage from bytes into GiB
        int currentGiB = (int)(stats.ShareUsageInBytes / ONE_GIBIBYTE);

        // This line sets the quota to be the current 
        // usage of the share plus the increase amount
        await share.SetQuotaAsync(currentGiB + increaseSizeInGiB);

        // Get the new quota and display it
        properties = await share.GetPropertiesAsync();
        Console.WriteLine($"New share quota: {properties.QuotaInGB} GiB");
    }
}

產生檔案或檔案共用的共用存取簽章Generate a shared access signature for a file or file share

從 Azure 檔案儲存體用戶端程式庫5.x 版開始,您可以為檔案共用或個別檔案產生共用存取簽章 (SAS) 。Beginning with version 5.x of the Azure Files client library, you can generate a shared access signature (SAS) for a file share or for an individual file.

下列範例方法會傳回指定共用中檔案的 SAS。The following example method returns a SAS on a file in the specified share.

//-------------------------------------------------
// Create a SAS URI for a file
//-------------------------------------------------
public Uri GetFileSasUri(string shareName, string filePath, DateTime expiration, ShareFileSasPermissions permissions)
{
    // Get the account details from app settings
    string accountName = ConfigurationManager.AppSettings["StorageAccountName"];
    string accountKey = ConfigurationManager.AppSettings["StorageAccountKey"];

    ShareSasBuilder fileSAS = new ShareSasBuilder()
    {
        ShareName = shareName,
        FilePath = filePath,

        // Specify an Azure file resource
        Resource = "f",

        // Expires in 24 hours
        ExpiresOn = expiration
    };

    // Set the permissions for the SAS
    fileSAS.SetPermissions(permissions);

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

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

    // Return the URI
    return fileSasUri.Uri;
}

如需建立和使用共用存取簽章的詳細資訊,請參閱 共用存取簽章的運作方式For more information about creating and using shared access signatures, see How a shared access signature works.

複製檔案Copy files

從 Azure 檔案儲存體用戶端程式庫5.x 版開始,您可以將檔案複製到另一個檔案、將檔案複製到 blob,或將 blob 複製到檔案。Beginning with version 5.x of the Azure Files client library, you can copy a file to another file, a file to a blob, or a blob to a file.

您也可以使用 AzCopy 將檔案複製到另一個檔案,或將 blob 複製到檔案,或複製到檔案中。You can also use AzCopy to copy one file to another or to copy a blob to a file or the other way around. 請參閱開始使用 AzCopySee Get started with AzCopy.

注意

如果要將 Blob 複製到檔案,或將檔案複製到 Blob,您必須使用共用存取簽章 (SAS) 來授權來源物件的存取全,即使是在相同的儲存體帳戶內進行複製也一樣。If you are copying a blob to a file, or a file to a blob, you must use a shared access signature (SAS) to authorize access to the source object, even if you are copying within the same storage account.

將檔案複製到另一個檔案Copy a file to another file

下列範例會將檔案複製到相同共用中的另一個檔案。The following example copies a file to another file in the same share. 您可以使用 共用金鑰驗證 來執行複製作業,因為這項作業會複製相同儲存體帳戶內的檔案。You can use Shared Key authentication to do the copy because this operation copies files within the same storage account.

//-------------------------------------------------
// Copy file within a directory
//-------------------------------------------------
public async Task CopyFileAsync(string shareName, string sourceFilePath, string destFilePath)
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Get a reference to the file we created previously
    ShareFileClient sourceFile = new ShareFileClient(connectionString, shareName, sourceFilePath);

    // Ensure that the source file exists
    if (await sourceFile.ExistsAsync())
    {
        // Get a reference to the destination file
        ShareFileClient destFile = new ShareFileClient(connectionString, shareName, destFilePath);

        // Start the copy operation
        await destFile.StartCopyAsync(sourceFile.Uri);

        if (await destFile.ExistsAsync())
        {
            Console.WriteLine($"{sourceFile.Uri} copied to {destFile.Uri}");
        }
    }
}

將檔案複製到 BlobCopy a file to a blob

下列範例會建立檔案,並將其複製到相同儲存體帳戶內的 Blob。The following example creates a file and copies it to a blob within the same storage account. 此範例會建立來源檔案的 SAS,供服務用來在複製作業期間授權來源檔案存取權。The example creates a SAS for the source file, which the service uses to authorize access to the source file during the copy operation.

//-------------------------------------------------
// Copy a file from a share to a blob
//-------------------------------------------------
public async Task CopyFileToBlobAsync(string shareName, string sourceFilePath, string containerName, string blobName)
{
    // Get a file SAS from the method created ealier
    Uri fileSasUri = GetFileSasUri(shareName, sourceFilePath, DateTime.UtcNow.AddHours(24), ShareFileSasPermissions.Read);

    // Get a reference to the file we created previously
    ShareFileClient sourceFile = new ShareFileClient(fileSasUri);

    // Ensure that the source file exists
    if (await sourceFile.ExistsAsync())
    {
        // Get the connection string from app settings
        string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

        // Get a reference to the destination container
        BlobContainerClient container = new BlobContainerClient(connectionString, containerName);

        // Create the container if it doesn't already exist
        await container.CreateIfNotExistsAsync();

        BlobClient destBlob = container.GetBlobClient(blobName);

        await destBlob.StartCopyFromUriAsync(sourceFile.Uri);

        if (await destBlob.ExistsAsync())
        {
            Console.WriteLine($"File {sourceFile.Name} copied to blob {destBlob.Name}");
        }
    }
}

您可以用相同方式將 Blob 複製到檔案。You can copy a blob to a file in the same way. 如果來源物件為 Blob,則請建立 SAS,以便在複製作業期間授權該 Blob 存取權。If the source object is a blob, then create a SAS to authorize access to that blob during the copy operation.

共用快照集Share snapshots

從 Azure 檔案儲存體用戶端程式庫的8.5 版開始,您可以建立共用快照集。Beginning with version 8.5 of the Azure Files client library, you can create a share snapshot. 您也可以列出或瀏覽共用快照集,並將共用快照集刪除。You can also list or browse share snapshots and delete share snapshots. 一旦建立,共用快照集就會是唯讀的。Once created, share snapshots are read-only.

建立共用快照集Create share snapshots

下列範例會建立檔案共用快照集。The following example creates a file share snapshot.

//-------------------------------------------------
// Create a share snapshot
//-------------------------------------------------
public async Task CreateShareSnapshotAsync(string shareName)
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instatiate a ShareServiceClient
    ShareServiceClient shareServiceClient = new ShareServiceClient(connectionString);

    // Instantiate a ShareClient which will be used to access the file share
    ShareClient share = shareServiceClient.GetShareClient(shareName);

    // Ensure that the share exists
    if (await share.ExistsAsync())
    {
        // Create a snapshot
        ShareSnapshotInfo snapshotInfo = await share.CreateSnapshotAsync();
        Console.WriteLine($"Snapshot created: {snapshotInfo.Snapshot}");
    }
}

列出共用快照集List share snapshots

下列範例會列出共用上的快照集。The following example lists the snapshots on a share.

//-------------------------------------------------
// List the snapshots on a share
//-------------------------------------------------
public void ListShareSnapshots()
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instatiate a ShareServiceClient
    ShareServiceClient shareServiceClient = new ShareServiceClient(connectionString);

    // Display each share and the snapshots on each share
    foreach (ShareItem item in shareServiceClient.GetShares(ShareTraits.All, ShareStates.Snapshots))
    {
        if (null != item.Snapshot)
        {
            Console.WriteLine($"Share: {item.Name}\tSnapshot: {item.Snapshot}");
        }
    }
}

列出共用快照集內的檔案和目錄List files and directories within share snapshots

下列範例會流覽共用快照集內的檔案和目錄。The following example browses files and directories within share snapshots.

//-------------------------------------------------
// List the snapshots on a share
//-------------------------------------------------
public void ListSnapshotContents(string shareName, string snapshotTime)
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instatiate a ShareServiceClient
    ShareServiceClient shareService = new ShareServiceClient(connectionString);

    // Get a ShareClient
    ShareClient share = shareService.GetShareClient(shareName);

    Console.WriteLine($"Share: {share.Name}");

    // Get as ShareClient that points to a snapshot
    ShareClient snapshot = share.WithSnapshot(snapshotTime);

    // Get the root directory in the snapshot share
    ShareDirectoryClient rootDir = snapshot.GetRootDirectoryClient();

    // Recursively list the directory tree
    ListDirTree(rootDir);
}

//-------------------------------------------------
// Recursively list a directory tree
//-------------------------------------------------
public void ListDirTree(ShareDirectoryClient dir)
{
    // List the files and directories in the snapshot
    foreach (ShareFileItem item in dir.GetFilesAndDirectories())
    {
        if (item.IsDirectory)
        {
            Console.WriteLine($"Directory: {item.Name}");
            ShareDirectoryClient subDir = dir.GetSubdirectoryClient(item.Name);
            ListDirTree(subDir);
        }
        else
        {
            Console.WriteLine($"File: {dir.Name}\\{item.Name}");
        }
    }
}

從共用快照集還原檔案共用或檔案Restore file shares or files from share snapshots

取得檔案共用的快照集,可讓您復原個別檔案或整個檔案共用。Taking a snapshot of a file share enables you to recover individual files or the entire file share.

您可以從檔案共用快照集還原檔案,方法是查詢檔案共用的共用快照集。You can restore a file from a file share snapshot by querying the share snapshots of a file share. 然後,您可以取得屬於特定共用快照集的檔案。You can then retrieve a file that belongs to a particular share snapshot. 您可以使用該版本直接讀取或還原檔案。Use that version to directly read or to restore the file.

//-------------------------------------------------
// Restore file from snapshot
//-------------------------------------------------
public async Task RestoreFileFromSnapshot(string shareName, string directoryName, string fileName, string snapshotTime)
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instatiate a ShareServiceClient
    ShareServiceClient shareService = new ShareServiceClient(connectionString);

    // Get a ShareClient
    ShareClient share = shareService.GetShareClient(shareName);

    // Get as ShareClient that points to a snapshot
    ShareClient snapshot = share.WithSnapshot(snapshotTime);

    // Get a ShareDirectoryClient, then a ShareFileClient to the snapshot file
    ShareDirectoryClient snapshotDir = snapshot.GetDirectoryClient(directoryName);
    ShareFileClient snapshotFile = snapshotDir.GetFileClient(fileName);

    // Get a ShareDirectoryClient, then a ShareFileClient to the live file
    ShareDirectoryClient liveDir = share.GetDirectoryClient(directoryName);
    ShareFileClient liveFile = liveDir.GetFileClient(fileName);

    // Restore the file from the snapshot
    ShareFileCopyInfo copyInfo = await liveFile.StartCopyAsync(snapshotFile.Uri);

    // Display the status of the operation
    Console.WriteLine($"Restore status: {copyInfo.CopyStatus}");
}

刪除共用快照集Delete share snapshots

下列範例會刪除檔案共用快照集。The following example deletes a file share snapshot.

//-------------------------------------------------
// Delete a snapshot
//-------------------------------------------------
public async Task DeleteSnapshotAsync(string shareName, string snapshotTime)
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instatiate a ShareServiceClient
    ShareServiceClient shareService = new ShareServiceClient(connectionString);

    // Get a ShareClient
    ShareClient share = shareService.GetShareClient(shareName);

    // Get a ShareClient that points to a snapshot
    ShareClient snapshotShare = share.WithSnapshot(snapshotTime);

    try
    {
        // Delete the snapshot
        await snapshotShare.DeleteIfExistsAsync();
    }
    catch (RequestFailedException ex)
    {
        Console.WriteLine($"Exception: {ex.Message}");
        Console.WriteLine($"Error code: {ex.Status}\t{ex.ErrorCode}");
    }
}

使用計量針對 Azure 檔案儲存體進行疑難排解Troubleshoot Azure Files by using metrics

Azure 儲存體分析支援 Azure 檔案儲存體的度量。Azure Storage Analytics supports metrics for Azure Files. 利用度量資料,您可以追蹤要求及診斷問題。With metrics data, you can trace requests and diagnose issues.

您可以從 Azure 入口網站啟用 Azure 檔案儲存體的計量。You can enable metrics for Azure Files from the Azure portal. 您也可以透過以程式設計方式啟用計量,方法是在 Azure 檔案儲存體用戶端程式庫中使用 REST API 或其中一個類比來呼叫「配置 檔案服務屬性 」作業。You can also enable metrics programmatically by calling the Set File Service Properties operation with the REST API or one of its analogs in the Azure Files client library.

下列程式碼範例示範如何使用 .NET 用戶端程式庫來啟用 Azure 檔案儲存體的計量。The following code example shows how to use the .NET client library to enable metrics for Azure Files.

//-------------------------------------------------
// Use metrics
//-------------------------------------------------
public async Task UseMetricsAsync()
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instatiate a ShareServiceClient
    ShareServiceClient shareService = new ShareServiceClient(connectionString);

    // Set metrics properties for File service
    await shareService.SetPropertiesAsync(new ShareServiceProperties()
    {
        // Set hour metrics
        HourMetrics = new ShareMetrics()
        {
            Enabled = true,
            IncludeApis = true,
            Version = "1.0",

            RetentionPolicy = new ShareRetentionPolicy()
            {
                Enabled = true,
                Days = 14
            }
        },

        // Set minute metrics
        MinuteMetrics = new ShareMetrics()
        {
            Enabled = true,
            IncludeApis = true,
            Version = "1.0",

            RetentionPolicy = new ShareRetentionPolicy()
            {
                Enabled = true,
                Days = 7
            }
        }
    });

    // Read the metrics properties we just set
    ShareServiceProperties serviceProperties = await shareService.GetPropertiesAsync();

    // Display the properties
    Console.WriteLine();
    Console.WriteLine($"HourMetrics.InludeApis: {serviceProperties.HourMetrics.IncludeApis}");
    Console.WriteLine($"HourMetrics.RetentionPolicy.Days: {serviceProperties.HourMetrics.RetentionPolicy.Days}");
    Console.WriteLine($"HourMetrics.Version: {serviceProperties.HourMetrics.Version}");
    Console.WriteLine();
    Console.WriteLine($"MinuteMetrics.InludeApis: {serviceProperties.MinuteMetrics.IncludeApis}");
    Console.WriteLine($"MinuteMetrics.RetentionPolicy.Days: {serviceProperties.MinuteMetrics.RetentionPolicy.Days}");
    Console.WriteLine($"MinuteMetrics.Version: {serviceProperties.MinuteMetrics.Version}");
    Console.WriteLine();
}

如果您遇到任何問題,您可以參考 Windows 中 Azure 檔案儲存體問題的疑難排解If you encounter any problems, you can refer to Troubleshoot Azure Files problems in Windows.

後續步驟Next steps

如需 Azure 檔案儲存體的詳細資訊,請參閱下列資源:For more information about Azure Files, see the following resources:

概念性文章和影片Conceptual articles and videos

檔案儲存體的工具支援Tooling support for File storage

參考資料Reference