Ontwikkelen voor Azure Files met .NET

Leer de basisbeginselen van het ontwikkelen van .NET-toepassingen die gebruikmaken van Azure Files voor het opslaan van gegevens. In dit artikel wordt beschreven hoe u een eenvoudige consoletoepassing maakt om het volgende te doen met .NET en Azure Files:

  • De inhoud van een bestand ophalen.
  • Stel de maximale grootte of het quotum voor een bestandsshare in.
  • Maak een Shared Access Signature (SAS) voor een bestand.
  • Een bestand kopiëren naar een ander bestand in hetzelfde opslagaccount.
  • Een bestand kopiëren naar een blob in hetzelfde opslagaccount.
  • Maak een momentopname van een bestandsshare.
  • Een bestand terugzetten vanuit een momentopname van een share.
  • Gebruik metrische gegevens van Azure Storage voor het oplossen van problemen.

Zie Wat is Azure Files? voor meer informatie over Azure Files.

Tip

Bekijk de opslagplaats met codevoorbeelden van Azure Storage

Raadpleeg onze lijst met Azure Storage-voorbeelden voor eenvoudig te gebruiken end-to-end Azure Storage-codevoorbeelden die u kunt downloaden en uitvoeren.

Van toepassing op

Bestands sharetype SMB NFS
Standaardbestandsshares (GPv2), LRS/ZRS Ja Nee
Standaardbestandsshares (GPv2), GRS/GZRS Ja Nee
Premium bestandsshares (FileStorage), LRS/ZRS Ja No

De .NET-API's

Azure Files biedt twee veelzijdige methoden voor het maken van clienttoepassingen: Server Message Block (SMB) en REST. Binnen .NET abstraheren de System.IO API's en Azure.Storage.Files.Shares deze benaderingen.

API Wanneer gebruikt u dit? Opmerkingen
System.IO Uw toepassing:
  • Moet bestanden lezen/schrijven met behulp van SMB
  • Wordt uitgevoerd op een apparaat met toegang tot uw Azure Files-account via poort 445
  • Hoeft geen beheerinstellingen van de bestandsshare te beheren
Bestands-I/O geïmplementeerd met Azure Files via SMB is over het algemeen hetzelfde als I/O met een netwerkbestandsshare of lokaal opslagapparaat. Zie de zelfstudie Consoletoepassing voor een inleiding tot een aantal functies in .NET, waaronder bestands-I/O.
Azure.Storage.Files.Shares Uw toepassing:
  • Kan geen toegang krijgen tot Azure Files met behulp van SMB op poort 445 vanwege firewall- of internetproviderbeperkingen
  • Vereist beheerfunctionaliteit, zoals de mogelijkheid tot het instellen van een quotum voor een bestandsshare of het maken van een Shared Access Signature (gedeelde-toegangshandtekening)
In dit artikel wordt het gebruik van Azure.Storage.Files.Shares voor bestands-I/O met REST in plaats van SMB en het beheer van de bestandsshare beschreven.

De consoletoepassing maken en de assembly verkrijgen

U kunt de Azure Files-clientbibliotheek gebruiken in elk type .NET-app. Deze apps omvatten Azure-cloud-, web-, desktop- en mobiele apps. In deze handleiding maken we een consoletoepassing voor het gemak.

Maak in Visual Studio een nieuwe Windows-consoletoepassing. In de volgende stappen ziet u hoe u een consoletoepassing maakt in Visual Studio 2019. De stappen zijn nagenoeg gelijk in andere versies van Visual Studio.

  1. Start Visual Studio en selecteer Een nieuw project maken.
  2. Kies in Een nieuw project makende optie Console-app (.NET Framework) voor C# en selecteer vervolgens Volgende.
  3. Voer in Uw nieuwe project configureren een naam in voor de app en selecteer Maken.

Voeg alle codevoorbeelden in dit artikel toe aan de Program klasse in het bestand Program.cs .

NuGet gebruiken om de vereiste pakketten te installeren

Raadpleeg deze pakketten in uw project:

U kunt NuGet gebruiken om de pakketten te verkrijgen. Volg deze stappen:

  1. Klik in Solution Explorer met de rechtermuisknop op uw project en kies NuGet-pakketten beheren.

  2. Selecteer in NuGet Package Managerde optie Bladeren. Zoek en kies Azure.Core en selecteer vervolgens Installeren.

    Met deze stap installeert u het pakket en de bijbehorende afhankelijkheden.

  3. Zoek en installeer deze pakketten:

    • Azure.Storage.Blobs
    • Azure.Storage.Files.Shares
    • System.Configuration.ConfigurationManager

Sla de referenties van uw opslagaccount op in het App.config-bestand

Sla vervolgens uw referenties op in het App.config-bestand van uw project. Dubbelklik in Solution Explorer op App.config het bestand en bewerk het bestand zodat het vergelijkbaar is met het volgende voorbeeld.

Vervang door myaccount de naam van uw opslagaccount en mykey door de sleutel van uw opslagaccount.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="StorageConnectionString" 
      value="DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=mykey;EndpointSuffix=core.windows.net" />
    <add key="StorageAccountName" value="myaccount" />
    <add key="StorageAccountKey" value="mykey" />
  </appSettings>
</configuration>

Notitie

De Azurite-opslagemulator biedt momenteel geen ondersteuning voor Azure Files. Uw connection string moet zich richten op een Azure-opslagaccount in de cloud om met Azure Files te kunnen werken.

Using-instructies toevoegen

Open in Solution Explorer het bestand Program.cs en voeg de volgende instructies toe aan het begin van het bestand.

using System;
using System.Configuration;
using System.IO;
using System.Threading.Tasks;
using Azure;
using Azure.Storage;
using Azure.Storage.Blobs;
using Azure.Storage.Files.Shares;
using Azure.Storage.Files.Shares.Models;
using Azure.Storage.Sas;

Via een programma toegang krijgen tot de bestandsshare

Voeg in het bestand Program.cs de volgende code toe om programmatisch toegang te krijgen tot de bestandsshare.

Met de volgende methode maakt u een bestandsshare als deze nog niet bestaat. De methode begint met het maken van een ShareClient-object op basis van een connection string. Het voorbeeld probeert vervolgens een bestand te downloaden dat u eerder hebt gemaakt. Roep deze methode aan vanuit Main().

//-------------------------------------------------
// Create a file share
//-------------------------------------------------
public async Task CreateShareAsync(string shareName)
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instantiate a ShareClient which will be used to create and manipulate the file share
    ShareClient share = new ShareClient(connectionString, shareName);

    // Create the share if it doesn't already exist
    await share.CreateIfNotExistsAsync();

    // Ensure that the share exists
    if (await share.ExistsAsync())
    {
        Console.WriteLine($"Share created: {share.Name}");

        // Get a reference to the sample directory
        ShareDirectoryClient directory = share.GetDirectoryClient("CustomLogs");

        // Create the directory if it doesn't already exist
        await directory.CreateIfNotExistsAsync();

        // Ensure that the directory exists
        if (await directory.ExistsAsync())
        {
            // Get a reference to a file object
            ShareFileClient file = directory.GetFileClient("Log1.txt");

            // Ensure that the file exists
            if (await file.ExistsAsync())
            {
                Console.WriteLine($"File exists: {file.Name}");

                // Download the file
                ShareFileDownloadInfo download = await file.DownloadAsync();

                // Save the data to a local file, overwrite if the file already exists
                using (FileStream stream = File.OpenWrite(@"downloadedLog1.txt"))
                {
                    await download.Content.CopyToAsync(stream);
                    await stream.FlushAsync();
                    stream.Close();

                    // Display where the file was saved
                    Console.WriteLine($"File downloaded: {stream.Name}");
                }
            }
        }
    }
    else
    {
        Console.WriteLine($"CreateShareAsync failed");
    }
}

De maximale grootte voor een bestandsshare instellen

Vanaf versie 5.x van de Azure Files-clientbibliotheek kunt u het quotum (maximale grootte) voor een bestandsshare instellen. U kunt ook controleren hoeveel gegevens er momenteel zijn opgeslagen in de share.

Als u het quotum voor een share instelt, wordt de totale grootte van de bestanden die op de share zijn opgeslagen, beperkt. Als de totale grootte van bestanden op de share het quotum overschrijdt, kunnen clients de grootte van bestaande bestanden niet vergroten. Clients kunnen ook geen nieuwe bestanden maken, tenzij deze bestanden leeg zijn.

In onderstaand voorbeeld ziet u hoe u het huidige gebruik voor een share controleert en een quotum voor de share instelt.

//-------------------------------------------------
// Set the maximum size of a share
//-------------------------------------------------
public async Task SetMaxShareSizeAsync(string shareName, int increaseSizeInGiB)
{
    const long ONE_GIBIBYTE = 10737420000; // Number of bytes in 1 gibibyte

    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instantiate a ShareClient which will be used to access the file share
    ShareClient share = new ShareClient(connectionString, shareName);

    // Create the share if it doesn't already exist
    await share.CreateIfNotExistsAsync();

    // Ensure that the share exists
    if (await share.ExistsAsync())
    {
        // Get and display current share quota
        ShareProperties properties = await share.GetPropertiesAsync();
        Console.WriteLine($"Current share quota: {properties.QuotaInGB} GiB");

        // Get and display current usage stats for the share
        ShareStatistics stats = await share.GetStatisticsAsync();
        Console.WriteLine($"Current share usage: {stats.ShareUsageInBytes} bytes");

        // Convert current usage from bytes into GiB
        int currentGiB = (int)(stats.ShareUsageInBytes / ONE_GIBIBYTE);

        // This line sets the quota to be the current 
        // usage of the share plus the increase amount
        await share.SetQuotaAsync(currentGiB + increaseSizeInGiB);

        // Get the new quota and display it
        properties = await share.GetPropertiesAsync();
        Console.WriteLine($"New share quota: {properties.QuotaInGB} GiB");
    }
}

Een Shared Access Signature genereren voor een bestand of bestandsshare

Vanaf versie 5.x van de Azure Files-clientbibliotheek kunt u een SAS (Shared Access Signature) genereren voor een bestandsshare of voor een afzonderlijk bestand.

De volgende voorbeeldmethode retourneert een SAS voor een bestand in de opgegeven share.

//-------------------------------------------------
// Create a SAS URI for a file
//-------------------------------------------------
public Uri GetFileSasUri(string shareName, string filePath, DateTime expiration, ShareFileSasPermissions permissions)
{
    // Get the account details from app settings
    string accountName = ConfigurationManager.AppSettings["StorageAccountName"];
    string accountKey = ConfigurationManager.AppSettings["StorageAccountKey"];

    ShareSasBuilder fileSAS = new ShareSasBuilder()
    {
        ShareName = shareName,
        FilePath = filePath,

        // Specify an Azure file resource
        Resource = "f",

        // Expires in 24 hours
        ExpiresOn = expiration
    };

    // Set the permissions for the SAS
    fileSAS.SetPermissions(permissions);

    // Create a SharedKeyCredential that we can use to sign the SAS token
    StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey);

    // Build a SAS URI
    UriBuilder fileSasUri = new UriBuilder($"https://{accountName}.file.core.windows.net/{fileSAS.ShareName}/{fileSAS.FilePath}");
    fileSasUri.Query = fileSAS.ToSasQueryParameters(credential).ToString();

    // Return the URI
    return fileSasUri.Uri;
}

Zie Hoe een shared access signature werkt voor meer informatie over het maken en gebruiken van handtekeningen voor gedeelde toegang.

Bestanden kopiëren

Vanaf versie 5.x van de Azure Files-clientbibliotheek kunt u een bestand kopiëren naar een ander bestand, een bestand naar een blob of een blob naar een bestand.

U kunt AzCopy ook gebruiken om het ene bestand naar het andere te kopiëren of om een blob naar een bestand te kopiëren of andersom. Raadpleeg Aan de slag met AzCopy.

Notitie

Als u een blob kopieert naar een bestand of een bestand naar een blob, moet u een Shared Access Signature (SAS) gebruiken om toegang tot het bronobject toe te staan, zelfs als u binnen hetzelfde opslagaccount kopieert.

Een bestand kopiëren naar een ander bestand

In het volgende voorbeeld wordt een bestand gekopieerd naar een ander bestand in dezelfde share. U kunt verificatie met gedeelde sleutel gebruiken om het kopiëren uit te voeren, omdat met deze bewerking bestanden in hetzelfde opslagaccount worden gekopieerd.

//-------------------------------------------------
// Copy file within a directory
//-------------------------------------------------
public async Task CopyFileAsync(string shareName, string sourceFilePath, string destFilePath)
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Get a reference to the file we created previously
    ShareFileClient sourceFile = new ShareFileClient(connectionString, shareName, sourceFilePath);

    // Ensure that the source file exists
    if (await sourceFile.ExistsAsync())
    {
        // Get a reference to the destination file
        ShareFileClient destFile = new ShareFileClient(connectionString, shareName, destFilePath);

        // Start the copy operation
        await destFile.StartCopyAsync(sourceFile.Uri);

        if (await destFile.ExistsAsync())
        {
            Console.WriteLine($"{sourceFile.Uri} copied to {destFile.Uri}");
        }
    }
}

Een bestand kopiëren naar een blob

In het volgende voorbeeld wordt een bestand gemaakt en vervolgens gekopieerd naar een blob in hetzelfde opslagaccount. In het voorbeeld wordt een SAS voor het bronbestand gemaakt, die tijdens de kopieerbewerking door de service wordt gebruikt om toegang tot het bronbestand toe te staan.

//-------------------------------------------------
// Copy a file from a share to a blob
//-------------------------------------------------
public async Task CopyFileToBlobAsync(string shareName, string sourceFilePath, string containerName, string blobName)
{
    // Get a file SAS from the method created ealier
    Uri fileSasUri = GetFileSasUri(shareName, sourceFilePath, DateTime.UtcNow.AddHours(24), ShareFileSasPermissions.Read);

    // Get a reference to the file we created previously
    ShareFileClient sourceFile = new ShareFileClient(fileSasUri);

    // Ensure that the source file exists
    if (await sourceFile.ExistsAsync())
    {
        // Get the connection string from app settings
        string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

        // Get a reference to the destination container
        BlobContainerClient container = new BlobContainerClient(connectionString, containerName);

        // Create the container if it doesn't already exist
        await container.CreateIfNotExistsAsync();

        BlobClient destBlob = container.GetBlobClient(blobName);

        await destBlob.StartCopyFromUriAsync(sourceFile.Uri);

        if (await destBlob.ExistsAsync())
        {
            Console.WriteLine($"File {sourceFile.Name} copied to blob {destBlob.Name}");
        }
    }
}

Op dezelfde manier kunt u een blob naar een bestand kopiëren. Als het bronobject een blob is, maakt u een SAS om tijdens de kopieerbewerking de toegang tot de blob toe te staan.

Momentopnamen van shares

Vanaf versie 8.5 van de Azure Files-clientbibliotheek kunt u een momentopname van een share maken. U kunt ook de lijst met momentopnamen van shares weergeven, door een lijst met momentopnamen van shares bladeren en momentopnamen van shares verwijderen. Zodra de momentopnamen van shares zijn gemaakt, zijn ze alleen-lezen.

Momentopnamen van shares maken

In het volgende voorbeeld wordt een momentopname van een bestandsshare gemaakt.

//-------------------------------------------------
// Create a share snapshot
//-------------------------------------------------
public async Task CreateShareSnapshotAsync(string shareName)
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instatiate a ShareServiceClient
    ShareServiceClient shareServiceClient = new ShareServiceClient(connectionString);

    // Instantiate a ShareClient which will be used to access the file share
    ShareClient share = shareServiceClient.GetShareClient(shareName);

    // Ensure that the share exists
    if (await share.ExistsAsync())
    {
        // Create a snapshot
        ShareSnapshotInfo snapshotInfo = await share.CreateSnapshotAsync();
        Console.WriteLine($"Snapshot created: {snapshotInfo.Snapshot}");
    }
}

Momentopnamen van shares opvragen

In het volgende voorbeeld worden de momentopnamen van een share weergegeven.

//-------------------------------------------------
// List the snapshots on a share
//-------------------------------------------------
public void ListShareSnapshots()
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instatiate a ShareServiceClient
    ShareServiceClient shareServiceClient = new ShareServiceClient(connectionString);

    // Display each share and the snapshots on each share
    foreach (ShareItem item in shareServiceClient.GetShares(ShareTraits.All, ShareStates.Snapshots))
    {
        if (null != item.Snapshot)
        {
            Console.WriteLine($"Share: {item.Name}\tSnapshot: {item.Snapshot}");
        }
    }
}

Bestanden en mappen weergeven in momentopnamen van shares

In het volgende voorbeeld worden bestanden en mappen in momentopnamen van shares bekeken.

//-------------------------------------------------
// List the snapshots on a share
//-------------------------------------------------
public void ListSnapshotContents(string shareName, string snapshotTime)
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instatiate a ShareServiceClient
    ShareServiceClient shareService = new ShareServiceClient(connectionString);

    // Get a ShareClient
    ShareClient share = shareService.GetShareClient(shareName);

    Console.WriteLine($"Share: {share.Name}");

    // Get as ShareClient that points to a snapshot
    ShareClient snapshot = share.WithSnapshot(snapshotTime);

    // Get the root directory in the snapshot share
    ShareDirectoryClient rootDir = snapshot.GetRootDirectoryClient();

    // Recursively list the directory tree
    ListDirTree(rootDir);
}

//-------------------------------------------------
// Recursively list a directory tree
//-------------------------------------------------
public void ListDirTree(ShareDirectoryClient dir)
{
    // List the files and directories in the snapshot
    foreach (ShareFileItem item in dir.GetFilesAndDirectories())
    {
        if (item.IsDirectory)
        {
            Console.WriteLine($"Directory: {item.Name}");
            ShareDirectoryClient subDir = dir.GetSubdirectoryClient(item.Name);
            ListDirTree(subDir);
        }
        else
        {
            Console.WriteLine($"File: {dir.Name}\\{item.Name}");
        }
    }
}

Bestandsshares of bestanden terugzetten vanuit momentopnamen van shares

Als u een momentopname van een bestandsshare maakt, kunt u afzonderlijke bestanden of de hele bestandsshare herstellen.

U kunt een bestand vanuit een momentopname van de bestandsshare herstellen door de momentopnamen van shares van een bestandsshare op te vragen. U kunt vervolgens een bestand ophalen dat deel uitmaakt van een bepaalde momentopname van een share. Gebruik die versie om het bestand rechtstreeks te lezen of te herstellen.

//-------------------------------------------------
// Restore file from snapshot
//-------------------------------------------------
public async Task RestoreFileFromSnapshot(string shareName, string directoryName, string fileName, string snapshotTime)
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instatiate a ShareServiceClient
    ShareServiceClient shareService = new ShareServiceClient(connectionString);

    // Get a ShareClient
    ShareClient share = shareService.GetShareClient(shareName);

    // Get as ShareClient that points to a snapshot
    ShareClient snapshot = share.WithSnapshot(snapshotTime);

    // Get a ShareDirectoryClient, then a ShareFileClient to the snapshot file
    ShareDirectoryClient snapshotDir = snapshot.GetDirectoryClient(directoryName);
    ShareFileClient snapshotFile = snapshotDir.GetFileClient(fileName);

    // Get a ShareDirectoryClient, then a ShareFileClient to the live file
    ShareDirectoryClient liveDir = share.GetDirectoryClient(directoryName);
    ShareFileClient liveFile = liveDir.GetFileClient(fileName);

    // Restore the file from the snapshot
    ShareFileCopyInfo copyInfo = await liveFile.StartCopyAsync(snapshotFile.Uri);

    // Display the status of the operation
    Console.WriteLine($"Restore status: {copyInfo.CopyStatus}");
}

Momentopnamen van shares verwijderen

In het volgende voorbeeld wordt een momentopname van een bestandsshare verwijderd.

//-------------------------------------------------
// Delete a snapshot
//-------------------------------------------------
public async Task DeleteSnapshotAsync(string shareName, string snapshotTime)
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instatiate a ShareServiceClient
    ShareServiceClient shareService = new ShareServiceClient(connectionString);

    // Get a ShareClient
    ShareClient share = shareService.GetShareClient(shareName);

    // Get a ShareClient that points to a snapshot
    ShareClient snapshotShare = share.WithSnapshot(snapshotTime);

    try
    {
        // Delete the snapshot
        await snapshotShare.DeleteIfExistsAsync();
    }
    catch (RequestFailedException ex)
    {
        Console.WriteLine($"Exception: {ex.Message}");
        Console.WriteLine($"Error code: {ex.Status}\t{ex.ErrorCode}");
    }
}

Problemen met Azure Files oplossen met behulp van metrische gegevens

Azure Opslaganalyse ondersteunt metrische gegevens voor Azure Files. Met metrische gegevens kunt u aanvragen volgen en problemen diagnosticeren.

U kunt metrische gegevens inschakelen voor Azure Files vanuit de Azure Portal. U kunt metrische gegevens ook programmatisch inschakelen door de bewerking Bestandsservice-eigenschappen instellen aan te roepen met de REST API of een van de analogen in de Azure Files-clientbibliotheek.

In het volgende codevoorbeeld ziet u hoe u de .NET-clientbibliotheek gebruikt om metrische gegevens in te schakelen voor Azure Files.

//-------------------------------------------------
// Use metrics
//-------------------------------------------------
public async Task UseMetricsAsync()
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instatiate a ShareServiceClient
    ShareServiceClient shareService = new ShareServiceClient(connectionString);

    // Set metrics properties for File service
    await shareService.SetPropertiesAsync(new ShareServiceProperties()
    {
        // Set hour metrics
        HourMetrics = new ShareMetrics()
        {
            Enabled = true,
            IncludeApis = true,
            Version = "1.0",

            RetentionPolicy = new ShareRetentionPolicy()
            {
                Enabled = true,
                Days = 14
            }
        },

        // Set minute metrics
        MinuteMetrics = new ShareMetrics()
        {
            Enabled = true,
            IncludeApis = true,
            Version = "1.0",

            RetentionPolicy = new ShareRetentionPolicy()
            {
                Enabled = true,
                Days = 7
            }
        }
    });

    // Read the metrics properties we just set
    ShareServiceProperties serviceProperties = await shareService.GetPropertiesAsync();

    // Display the properties
    Console.WriteLine();
    Console.WriteLine($"HourMetrics.InludeApis: {serviceProperties.HourMetrics.IncludeApis}");
    Console.WriteLine($"HourMetrics.RetentionPolicy.Days: {serviceProperties.HourMetrics.RetentionPolicy.Days}");
    Console.WriteLine($"HourMetrics.Version: {serviceProperties.HourMetrics.Version}");
    Console.WriteLine();
    Console.WriteLine($"MinuteMetrics.InludeApis: {serviceProperties.MinuteMetrics.IncludeApis}");
    Console.WriteLine($"MinuteMetrics.RetentionPolicy.Days: {serviceProperties.MinuteMetrics.RetentionPolicy.Days}");
    Console.WriteLine($"MinuteMetrics.Version: {serviceProperties.MinuteMetrics.Version}");
    Console.WriteLine();
}

Als u problemen ondervindt, raadpleegt u Problemen oplossen Azure Files.

Volgende stappen

Zie de volgende bronnen voor meer informatie over Azure Files:

Conceptuele artikelen en video's

Hulpprogramma-ondersteuning voor File Storage

Referentie

Zie Codevoorbeelden met .NET versie 11.x voor gerelateerde codevoorbeelden met behulp van afgeschafte .NET versie 11.x SDK's.