Codebeispiele für Azure File Share mit Clientbibliotheken für .NET, Version 11.x

Dieser Artikel zeigt Codebeispiele, die Version 11.x der Azure File Storage-Clientbibliothek für .NET verwenden.

Am 31. März 2023 haben wir die Unterstützung für Azure SDK-Bibliotheken eingestellt, die nicht den aktuellen Azure SDK-Richtlinien entsprachen. Die neuen Azure SDK-Bibliotheken werden regelmäßig aktualisiert, um konsistente Erfahrungen zu ermöglichen und Ihren Sicherheitsstatus zu stärken. Es wird empfohlen, auf die neuen Azure SDK-Bibliotheken umzusteigen, um die neuen Funktionen und wichtigen Sicherheitsupdates zu nutzen.

Obwohl die älteren Bibliotheken noch über den 31. März 2023 hinaus verwendet werden können, erhalten sie keinen offiziellen Support und keine Updates mehr von Microsoft. Weitere Informationen finden Sie in der Ankündigung der Supporteinstellung.

Voraussetzungen

Installieren Sie diese Pakete in Ihrem Projektverzeichnis:

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

Fügen Sie die folgenden using-Anweisungen hinzu:

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

Zugreifen auf die Dateifreigabe

Verwandter Artikel: Entwickeln für Azure Files mit .NET

Fügen Sie den folgenden Code hinzu, um auf die Dateifreigabe zuzugreifen:

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

Festlegen der maximalen Größe für eine Dateifreigabe

Verwandter Artikel: Entwickeln für Azure Files mit .NET

Ab Version 5.x der Azure Files-Clientbibliothek können Sie das Kontingent (die maximale Größe) für eine Dateifreigabe festlegen. Sie können auch überprüfen, wie viele Daten sich aktuell auf der Freigabe befinden.

Eine Festlegung des Kontingents für eine Freigabe begrenzt die Gesamtgröße der Dateien, die in der Freigabe gespeichert werden. Wenn die Gesamtgröße der Dateien in der Freigabe das Kontingent überschreitet, können Clients die Größe vorhandener Dateien nicht erhöhen. Clients können auch keine neuen Dateien erstellen, außer wenn diese Dateien leer sind.

Das folgende Beispiel zeigt, wie Sie die aktuelle Nutzung einer Freigabe überprüfen und das Kontingent für die Freigabe festlegen.

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

Generieren einer SAS für eine Datei oder Dateifreigabe

Ab Version 5.x der Azure Files-Clientbibliothek können Sie eine SAS (Shared Access Signature) für eine Dateifreigabe oder für eine einzelne Datei generieren.

Sie können auch eine gespeicherte Zugriffsrichtlinie für eine Dateifreigabe erstellen, um Shared Access Signatures zu verwalten. Es wird empfohlen, eine gespeicherte Zugriffsrichtlinie zu erstellen, weil Sie die SAS widerrufen können, wenn sie gefährdet ist. Im folgenden Beispiel wird eine gespeicherte Zugriffsrichtlinie für eine Freigabe erstellt. Diese Richtlinie wird verwendet, um die Einschränkungen bei einer SAS für eine Datei in der Freigabe bereitzustellen.

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

Kopieren von Dateien

Verwandter Artikel: Entwickeln für Azure Files mit .NET

Ab Version 5.x der Azure Files-Clientbibliothek können Sie eine Datei in eine andere Datei, eine Datei in ein Blob oder ein Blob in eine Datei kopieren.

Sie können auch AzCopy verwenden, um eine Datei in eine andere oder ein Blob in eine Datei (oder umgekehrt) zu kopieren. Informationen finden Sie unter Übertragen von Daten mit AzCopy v10.

Hinweis

Wenn Sie ein BLOB in eine Datei oder eine Datei in ein BLOB kopieren, müssen Sie eine SAS verwenden, um den Zugriff auf das Quellobjekt zu autorisieren. Dies gilt selbst dann, wenn Sie innerhalb desselben Speicherkontos kopieren.

Kopieren einer Datei in eine andere Datei

Im folgenden Beispiel wird eine Datei in eine andere Datei in derselben Freigabe kopiert. Für den Kopiervorgang können Sie die Authentifizierung mit gemeinsam verwendetem Schlüssel verwenden, weil dieser Vorgang Dateien innerhalb ein und desselben Speicherkontos kopiert.

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

Kopieren einer Datei in ein Blob

Im folgenden Beispiel wird eine Datei erstellt und in ein Blob im selben Speicherkonto kopiert. In dem Beispiel wird für die Quelldatei eine SAS erstellt, die der Dienst dazu verwendet, während des Kopiervorgangs den Zugriff auf die Quelldatei zu autorisieren.

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

Auf gleiche Weise können Sie ein BLOB in eine Datei kopieren. Wenn das Quellobjekt ein BLOB ist, erstellen Sie eine SAS, um den Zugriff auf dieses BLOB während des Kopiervorgangs zu autorisieren.

Freigabemomentaufnahmen

Verwandter Artikel: Entwickeln für Azure Files mit .NET

Ab Version 8.5 der Azure Files-Clientbibliothek können Sie eine Freigabemomentaufnahme erstellen. Außerdem können Sie Freigabemomentaufnahmen auflisten, durchsuchen und löschen. Freigabemomentaufnahmen sind schreibgeschützt.

Erstellen von Freigabemomentaufnahmen

Das folgende Beispiel erstellt eine Momentaufnahme der Freigabe:

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

Auflisten von Freigabemomentaufnahmen

Das folgende Beispiel listet die Momentaufnahmen in einer Freigabe auf:

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

Auflisten von Dateien und Verzeichnissen in Freigabemomentaufnahmen

Das folgende Beispiel durchsucht Dateien und Verzeichnisse in Momentaufnahmen einer Freigabe:

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

Wiederherstellen von Dateifreigaben oder Dateien aus Freigabemomentaufnahmen

Die Erstellung einer Momentaufnahme von einer Dateifreigabe ermöglicht die Wiederherstellung einzelner Dateien oder der gesamten Dateifreigabe.

Zum Wiederherstellen einer Datei aus einer Dateifreigabemomentaufnahme können Sie die Freigabemomentaufnahmen einer Dateifreigabe abfragen. Danach können Sie eine Datei abrufen, die zu einer bestimmten Freigabemomentaufnahme gehört. Verwenden Sie diese Version, um die Datei direkt zu lesen oder wiederherzustellen.

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

Löschen von Freigabemomentaufnahmen

Das folgende Beispiel löscht die Momentaufnahme einer Freigabe:

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

Behandeln von Azure Files-Problemen mithilfe von Metriken

Verwandter Artikel: Entwickeln für Azure Files mit .NET

Azure Storage Analytics unterstützt Metriken für Azure Files. Mit Metrikdaten können Sie Anforderungen verfolgen und Probleme diagnostizieren.

Die Metriken für Azure Files können über das Azure-Portal aktiviert werden. Sie können Metriken auch programmgesteuert aktivieren, indem Sie den Vorgang Set File Service Properties mit der REST-API oder einem entsprechenden Vorgang in der Azure Files-Clientbibliothek aufrufen.

Das folgende Codebeispiel zeigt, wie Sie die .NET-Clientbibliothek zum Aktivieren von Metriken für Azure Files verwenden.

Fügen Sie Ihrer Datei Program.cs zunächst die folgenden using-Anweisungen zusätzlich zu den oben hinzugefügten Anweisungen hinzu:

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

Obwohl bei Azure-Blobs, Azure-Tabellen und Azure-Warteschlangen der gemeinsam genutzte Typ ServiceProperties im Namespace Microsoft.Azure.Storage.Shared.Protocol verwendet wird, verwendet Azure Files seinen eigenen Typ (FileServiceProperties) im Namespace Microsoft.Azure.Storage.File.Protocol. Sie müssen aber in Ihrem Code auf beide Namespaces verweisen, damit der folgende Code kompiliert werden kann.

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