Поделиться через


Примеры кода общей папки Azure с помощью клиентских библиотек .NET версии 11.x

В этой статье приведены примеры кода, использующих клиентскую библиотеку Azure File Share версии 11.x для .NET.

31 марта 2023 г. мы прекратили поддержку библиотек Azure SDK, которые не соответствуют текущим рекомендациям Azure SDK. Новые библиотеки azure SDK регулярно обновляются для обеспечения согласованного взаимодействия и укрепления системы безопасности. Рекомендуется перейти на новые библиотеки пакета SDK Azure, чтобы воспользоваться новыми возможностями и критически важными обновлениями безопасности.

Хотя старые библиотеки по-прежнему могут использоваться после 31 марта 2023 г., они больше не будут получать официальную поддержку и обновления от Корпорации Майкрософт. Дополнительные сведения см. в объявлении о завершении поддержки.

Необходимые компоненты

Установите эти пакеты в каталоге проекта:

  • 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

Доступ к общей папке

Связанная статья: Разработка для Azure Files с помощью .NET

Добавьте следующий код для доступа к общей папке:

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

Установите максимальный размер для файлового ресурса

Связанная статья: Разработка приложений для Azure Files на .NET

Клиентская библиотека Файлов 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);
}

Создание подписи общего доступа для файла или файлового ресурса

Начиная с версии 5.x клиентской библиотеки Файлов Azure, можно создать подписанный URL-адрес (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());
}

Копирование файлов

Связанная статья: Разработка для файлов Azure с использованием .NET

Начиная с версии 5.x клиентской библиотеки Файлов Azure, можно скопировать файл в другой файл, файл в BLOB-объект или BLOB-объект в файл.

AzCopy можно использовать для копирования одного файла в другой, а также копирования BLOB-объекта в файл или наоборот. См. Начало работы с AzCopy.

Примечание.

При копировании большого двоичного объекта в файл или файла в большой двоичный объект необходимо использовать подписанный URL-адрес (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

В приведенном ниже примере файл создается и копируется в большой двоичный объект в пределах одной и той же учетной записи хранения. В примере для исходного файла создается 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-объект в файл. Если исходным объектом является большой двоичный объект, создайте SAS для авторизации доступа к этому объекту во время операции копирования.

Делитесь моментальными снимками

Связанная статья: Разработка для Azure Files на .NET

Начиная с версии 8.5 клиентской библиотеки Файлов Azure, можно создавать моментальные снимки общих папок. Можно также получить список моментальных снимков общих ресурсов, просмотреть и удалить их. После создания моментальные снимки становятся доступными только для чтения.

Создайте моментальные снимки общих папок

В следующем примере создается моментальный снимок общей папки:

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" с помощью метрик

Связанная статья: Разработка файлов Azure с помощью .NET

Аналитика Службы хранилища Azure поддерживает метрики для Файлов Azure. Данные метрик позволяют отслеживать запросы и диагностировать проблемы.

Вы можете включить метрики для Файлов Azure с помощью портала Azure. Кроме того, вы можете включить метрики программным путем. Для этого вызовите операцию Set File Service Properties через интерфейс REST API или любой ее аналог из имеющихся в клиентской библиотеке Файлов Azure.

В следующем примере кода показано, как использовать клиентскую библиотеку для .NET, чтобы включить метрики для Файлов Azure.

Сначала добавьте следующие директивы using в файл Program.cs рядом с добавленными ранее:

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

Azure Blobs, Azure Tables и Azure Queues используют общий тип ServiceProperties в пространстве имен Microsoft.Azure.Storage.Shared.Protocol, тогда как Azure Files использует собственный тип FileServiceProperties в пространстве имен Microsoft.Azure.Storage.File.Protocol. Для обеспечения компиляции приведенного ниже кода ваш код должен ссылаться на оба этих пространства имен.

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