使用 .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 stored 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.Storage.FileMicrosoft.Azure.Storage.File 应用程序:Your application:
  • 由于防火墙或 ISP 约束,无法使用 SMB 在端口 445 上访问 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(而不是 SMB)将 Microsoft.Azure.Storage.File 用于文件 I/O 以及如何管理文件共享。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. 在“创建新项目” 中,选择用于 C# 的“控制台应用(.NET Framework)” ,然后选择“下一步” 。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.Storage.Blob”,然后选择“安装”。 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.Storage.CommonMicrosoft.Azure.Storage.Common
    • Microsoft.Azure.Storage.FileMicrosoft.Azure.Storage.File
    • Microsoft.Azure.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 替换为你的存储帐户名,将 mykey 替换为你的存储帐户密钥。Replace 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==;EndpointSuffix=core.chinacloudapi.cn" />
    </appSettings>
</configuration>

备注

最新版本的 Azure 存储模拟器不支持 Azure 文件。The latest version of the Azure Storage Emulator does not support Azure Files. 连接字符串必须针对云中要使用 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 的 Azure Configuration Manager 库 提供用于分析配置文件中连接字符串的类。The Azure Configuration Manager Library for .NET provides a class for parsing a connection string from a configuration file. 无论客户端应用程序是在台式机、移动设备、Azure 虚拟机还是在 Azure 云服务中运行,都可以使用 CloudConfigurationManager 类分析配置设置。The CloudConfigurationManager class parses configuration settings regardless of whether the client application is running 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 directive:

using Microsoft.Azure; //Namespace for CloudConfigurationManager
using Microsoft.WindowsAzure.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 like 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 stored access policy on a file share to manage shared access signatures. 我们建议创建一个存储访问策略,因为它可以在 SAS 泄密时让你撤销 SAS。We recommend creating a stored access policy because it lets you revoke the SAS if it becomes compromised.

以下示例在共享上创建一个存储访问策略。The following example creates a stored 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 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());
}

若要详细了解如何创建和使用共享访问签名,请参阅共享访问签名的工作原理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. 请参阅 AzCopy 入门See 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,服务在复制操作期间使用该 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 = dirInSnapshot.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

文件存储的工具支持Tooling support for File storage

参考Reference

博客文章Blog posts