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

本教學課程將示範基本概念,說明如何利用 .NET 開發使用 Azure 檔案服務來儲存檔案資料的應用程式。This tutorial demonstrates the basics of using .NET to develop applications that use Azure Files to store file data. 本教學課程會建立簡單的主控台應用程式,以使用 .NET 和 Azure 檔案儲存體執行基本動作:This tutorial creates a simple console application to do basic actions with .NET and Azure Files:

  • 取得檔案的內容。Get the contents of a file.
  • 設定檔案共用的大小上限或配額Set the maximum size or quota for the file share.
  • 為使用共用上所定義之共用存取原則的檔案建立共用存取簽章 (SAS 金鑰)。Create a shared access signature (SAS key) for a file that uses a shared access policy defined on the share.
  • 將檔案複製到相同儲存體帳戶中的另一個檔案。Copy a file to another file in the same storage account.
  • 將檔案複製到相同儲存體帳戶中的 Blob。Copy a file to a blob in the same storage account.
  • 使用 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.IOWindowsAzure.Storage Api 會將這些方法抽象化。Within .NET, the System.IO and WindowsAzure.Storage 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
透過 SMB Azure 檔案儲存體執行的檔案 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.
Microsoft. Azure 儲存檔案Microsoft.Azure.Storage.File 您的應用程式: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
本文示範如何使用 REST 來執行檔案 i/o 的 Microsoft.Azure.Storage.File,而不是 SMB 及檔案共用的管理。This article demonstrates the use of Microsoft.Azure.Storage.File for file I/O using REST instead of SMB and management of the file share.

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

在 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.cs 檔案的 Main() 方法。You can add all the code examples in this tutorial to the Main() method of your console application's Program.cs file.

您可以在任何類型的 .NET 應用程式中使用 Azure 儲存體用戶端程式庫。You can use the Azure Storage client library in any type of .NET application. 這些類型包括 Azure 雲端服務或 web 應用程式,以及桌面和行動應用程式。These types include an Azure cloud service or web app, and desktop and mobile applications. 在本指南中,為求簡化,我們會使用主控台應用程式。In this guide, we use a console application for simplicity.

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

請參閱您專案中的這些套件,以完成本教學課程:Refer to these packages in your project to complete this tutorial:

您可以使用 NuGet 來取得這兩個封裝。You can use NuGet to obtain both 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. 然後,搜尋並選擇 [ Microsoft. Azure],然後選取 [安裝]。Then search for and choose Microsoft.Azure.Storage.Blob, and then select Install.

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

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

    • Microsoft. Azure 儲存體。通用Microsoft.Azure.Storage.Common
    • Microsoft. Azure 儲存檔案Microsoft.Azure.Storage.File
    • ConfigurationManagerMicrosoft.Azure.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 取代為您的儲存體帳戶名稱,並使用您的儲存體帳戶金鑰來 mykeyReplace myaccount with your storage account name and mykey with your storage account key.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <appSettings>
        <add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=StorageAccountKeyEndingIn==" />
    </appSettings>
</configuration>

注意

最新版本的 Azure 儲存體模擬器不支援 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 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 的 Microsoft Azure Configuration Manager 程式庫 會提供一個類別,可用來剖析組態檔中的連接字串。The Microsoft Azure Configuration Manager Library for .NET provides a class for parsing a connection string from a configuration file. CloudConfigurationManager類別會剖析設定。The CloudConfigurationManager class parses configuration settings. 它會針對在桌面上、行動裝置、Azure 虛擬機器或 Azure 雲端服務中執行的用戶端應用程式,剖析其設定。It parses settings for client applications that run on the desktop, on a mobile device, in an Azure virtual machine, or in an Azure cloud service.

若要參考 CloudConfigurationManager 封裝,請新增下列 using 指示詞:To reference the CloudConfigurationManager package, add the following using directives:

using Microsoft.Azure; //Namespace for CloudConfigurationManager
using Microsoft.Azure.Storage;

以下範例示範如何從組態檔擷取連接字串:Here's an example that shows how to retrieve a connection string from a configuration file:

// Parse the connection string and return a reference to the storage account.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

是否使用 Azure Configuration Manager 可由您選擇。Using the Azure Configuration Manager is optional. 您也可以使用 API (例如 .NET Framework 的ConfigurationManager 類別)。You can also use an API such as the .NET Framework's ConfigurationManager Class.

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

接下來,在上方顯示的程式碼之後,將下列內容新增至 Main() 方法,以取得連接字串。Next, add the following content to the Main() method, after the code shown above, to retrieve the connection string. 這段程式碼會取得我們稍早建立之檔案的參考,並輸出其內容。This code gets a reference to the file we created earlier and outputs its contents.

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

執行主控台應用程式以查看此輸出。Run the console application to see the output.

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

從 Azure 儲存體用戶端程式庫的5.x 版開始,您可以設定檔案共用的配額(大小上限)。Beginning with version 5.x of the Azure Storage 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 set on the share, clients can't increase the size of existing files. 除非這些檔案是空的,否則用戶端無法建立新檔案。Clients 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.

// 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} GB", stats.Usage.ToString());

    // Specify the maximum size of the share, in GB.
    // This line sets the quota to be 10 GB 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} GB", share.Properties.Quota);
}

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

從 Azure 儲存體用戶端程式庫 5.x 版開始,您可以產生檔案共用或個別檔案的共用存取簽章 (SAS)。Beginning with version 5.x of the Azure Storage Client Library, 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. 我們建議您建立共用存取原則,因為它可讓您在 SAS 遭到入侵時撤銷它。We recommend creating a shared access policy because it lets you revoke the SAS if it becomes compromised.

下列範例會在共用上建立共用存取原則。The following example creates a shared access policy on a share. 此範例會使用該原則,為共用中的檔案提供 SAS 的條件約束。The example uses that policy to provide the constraints for a SAS on a file in the share.

// 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 shared 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 shared 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());
}

如需建立和使用共用存取簽章的詳細資訊,請參閱共用存取簽章的運作方式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 Storage Client Library, you can copy a file to another file, a file to a blob, or a blob to a file. 在接下來的章節中,我們會示範如何以程式設計方式執行這些複製作業。In the next sections, we demonstrate how to do these copy operations programmatically.

您也可以使用 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. 因為這項複製作業會在相同儲存體帳戶中的檔案之間複製,所以您可以使用共用金鑰驗證來進行複製。Because this copy operation copies between files in the same storage account, you can use Shared Key authentication to do the copy.

// 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());
        }
    }
}

將檔案複製到 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.

// 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 複製到檔案。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 Storage Client Library, you can create a share snapshot. 您也可以列出或瀏覽共用快照集,並將共用快照集刪除。You can also list or browse share snapshots and delete share snapshots. 共用快照集是唯讀的,因此共用快照集上不允許任何寫入作業。Share snapshots are read-only so no write operations are allowed on share snapshots.

建立共用快照集Create share snapshots

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

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

列出共用快照集List share snapshots

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

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

流覽共用快照集內的檔案和目錄Browse files and directories within share snapshots

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

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

列出共用和共用快照集,並從共用快照集還原檔案共用或檔案List shares and share snapshots and restore file shares or files from share snapshots

擷取檔案共用的快照集可讓您在未來將個別檔案或整個檔案共用復原。Taking a snapshot of a file share enables you to recover individual files or the entire the file share in the future.

您可以從檔案共用快照集還原檔案,方法是查詢檔案共用的共用快照集。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 either directly read and compare or to restore.

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

刪除共用快照集Delete share snapshots

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

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

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

Azure 儲存體分析現在支援 Azure 檔案服務的計量。Azure Storage Analytics now 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. 您也可以用程式設計方式啟用計量,方法是在儲存體用戶端程式庫中,使用 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 Storage Client Library.

下列程式碼範例會示範如何使用適用於 .NET 的儲存體用戶端程式庫,啟用 Azure 檔案服務的計量。The following code example shows how to use the Storage Client Library for .NET to enable metrics for Azure Files.

首先,將下列 using 指示詞新增至您的 Program.cs 檔案,以及您在上方新增的指示詞:First, add the following using directives to your Program.cs file, along with the ones you added above:

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 類型。Although Azure Blobs, Azure Tables, and Azure Queues use the shared ServiceProperties type in the Microsoft.Azure.Storage.Shared.Protocol namespace, Azure Files uses its own type, the FileServiceProperties type in the Microsoft.Azure.Storage.File.Protocol namespace. 不過,您必須從程式碼參考這兩個命名空間,才能編譯下列程式碼。You must reference both namespaces from your code, however, for the following code to compile.

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

如果您遇到任何問題,您可以參閱疑難排解 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

部落格文章Blog posts