Przykłady kodu udziału plików platformy Azure przy użyciu bibliotek klienckich platformy .NET w wersji 11.x

W tym artykule przedstawiono przykłady kodu, które używają wersji 11.x biblioteki klienta udziału plików platformy Azure dla platformy .NET.

31 marca 2023 r. wycofaliśmy obsługę bibliotek zestawu Azure SDK, które nie są zgodne z bieżącymi wytycznymi dotyczącymi zestawu Azure SDK. Nowe biblioteki zestawu Azure SDK są regularnie aktualizowane w celu zapewnienia spójnych środowisk i wzmocnienia stanu zabezpieczeń. Zaleca się przejście do nowych bibliotek zestawu Azure SDK w celu skorzystania z nowych możliwości i krytycznych aktualizacji zabezpieczeń.

Mimo że starsze biblioteki mogą być nadal używane poza 31 marca 2023 r., nie będą już otrzymywać oficjalnej pomocy technicznej i aktualizacji od firmy Microsoft. Aby uzyskać więcej informacji, zobacz ogłoszenie o wycofaniu pomocy technicznej.

Wymagania wstępne

Zainstaluj te pakiety w katalogu projektu:

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

Dodaj następujące using dyrektywy:

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

Uzyskiwanie dostępu do udziału plików

Powiązany artykuł: Programowanie dla Azure Files za pomocą platformy .NET

Dodaj następujący kod, aby uzyskać dostęp do udziału plików:

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

Ustawianie maksymalnego rozmiaru udziału plików

Powiązany artykuł: Programowanie dla Azure Files za pomocą platformy .NET

Począwszy od wersji 5.x biblioteki klienta Azure Files, można ustawić limit przydziału (maksymalny rozmiar) dla udziału plików. Można również sprawdzić, ile danych jest obecnie przechowywanych w udziale.

Ustawienie limitu przydziału udziału ogranicza całkowity rozmiar plików przechowywanych w udziale. Jeśli całkowity rozmiar plików w udziale przekracza limit przydziału, klienci nie mogą zwiększyć rozmiaru istniejących plików. Klienci nie mogą również tworzyć nowych plików, chyba że te pliki są puste.

W poniższym przykładzie pokazano, jak sprawdzić bieżące użycie udziału oraz jak ustawić limit przydziału w udziale.

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

Generowanie sygnatury dostępu współdzielonego dla pliku lub udziału plików

Począwszy od wersji 5.x biblioteki klienta Azure Files, można wygenerować sygnaturę dostępu współdzielonego (SAS) dla udziału plików lub dla pojedynczego pliku.

Można również utworzyć przechowywane zasady dostępu w udziale plików w celu zarządzania sygnaturami dostępu współdzielonego. Zalecamy utworzenie przechowywanych zasad dostępu, ponieważ umożliwia odwołanie sygnatury dostępu współdzielonego w przypadku naruszenia zabezpieczeń. Poniższy przykład tworzy przechowywane zasady dostępu w udziale. W tym przykładzie użyto tych zasad w celu zapewnienia ograniczeń dla sygnatury dostępu współdzielonego w pliku w udziale.

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

Kopiowanie plików

Powiązany artykuł: Programowanie dla Azure Files za pomocą platformy .NET

Począwszy od wersji 5.x biblioteki klienta Azure Files, można skopiować plik do innego pliku, pliku do obiektu blob lub obiektu blob do pliku.

Możesz również użyć narzędzia AzCopy, aby skopiować jeden plik do innego lub skopiować obiekt blob do pliku lub w drugą stronę. Zobacz Wprowadzenie do narzędzia AzCopy.

Uwaga

W przypadku kopiowania obiektu blob do pliku lub pliku do obiektu blob konieczne jest autoryzowanie dostępu do obiektu źródłowego za pomocą sygnatury dostępu współdzielonego, nawet jeśli kopiowanie odbywa się w ramach tego samego konta magazynu.

Kopiowanie pliku do innego pliku

Poniższy przykładowy kod kopiuje plik do innego pliku w tym samym udziale. Możesz użyć uwierzytelniania klucza współdzielonego , aby wykonać kopię, ponieważ ta operacja kopiuje pliki na tym samym koncie magazynu.

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

Kopiowanie pliku do obiektu blob

Poniższy przykładowy kod tworzy plik i kopiuje go do obiektu blob w ramach tego samego konta magazynu. Dla pliku źródłowego tworzona jest sygnatura dostępu współdzielonego, za pomocą której usługa autoryzuje dostęp do tego pliku podczas operacji kopiowania.

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

W ten sam sposób można skopiować obiekt blob do pliku. Jeśli obiekt źródłowy jest obiektem blob, utwórz sygnaturę dostępu współdzielonego w celu autoryzacji dostępu do tego obiektu blob podczas operacji kopiowania.

Migawki udziałów

Powiązany artykuł: Programowanie dla Azure Files za pomocą platformy .NET

Począwszy od wersji 8.5 biblioteki klienta Azure Files, można utworzyć migawkę udziału. Można również wyświetlać listę migawek udziałów oraz je przeglądać i usuwać. Po utworzeniu migawki udziałów są tylko do odczytu.

Tworzenie migawek udziałów

Poniższy przykład tworzy migawkę udziału plików:

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

Wyświetlanie listy migawek udziałów

Poniższy przykład zawiera listę migawek w udziale:

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

Wyświetlanie listy plików i katalogów w ramach migawek udziałów

Poniższy przykład umożliwia przeglądanie plików i katalogów w ramach migawek udziałów:

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

Przywracanie udziałów plików lub plików z migawek udziałów

Utworzenie migawki udziału plików umożliwia odzyskanie pojedynczych plików lub całego udziału plików.

Aby przywrócić plik z migawki udziału plików, można utworzyć zapytanie o migawki udziałów w udziale plików. Następnie można pobrać plik należący do określonej migawki udziału. Użyj tej wersji, aby bezpośrednio odczytać lub przywrócić plik.

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

Usuwanie migawek udziałów

Poniższy przykład usuwa migawkę udziału plików:

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

Rozwiązywanie problemów z Azure Files przy użyciu metryk

Powiązany artykuł: Programowanie dla Azure Files za pomocą platformy .NET

Usługa Azure analityka magazynu obsługuje metryki dla Azure Files. Dane metryk umożliwiają śledzenie żądań i diagnozowanie problemów.

Metryki dla Azure Files można włączyć z poziomu Azure Portal. Metryki można również włączyć programowo, wywołując operację Ustaw właściwości usługi plików za pomocą interfejsu API REST lub jedną z jego analogii w bibliotece klienta Azure Files.

Poniższy przykład kodu pokazuje, jak za pomocą biblioteki klienta platformy .NET włączyć metryki dla Azure Files.

Najpierw dodaj następujące using dyrektywy do pliku Program.cs wraz z dodanymi powyżej:

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

Chociaż obiekty blob platformy Azure, tabele platformy Azure i kolejki platformy Azure używają typu udostępnionego ServiceProperties w Microsoft.Azure.Storage.Shared.Protocol przestrzeni nazw, Azure Files używa własnego typu, FileServiceProperties typ w Microsoft.Azure.Storage.File.Protocol przestrzeni nazw. Należy jednak odwołać się do obu przestrzeni nazw z kodu, aby skompilować następujący kod.

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