Ontwikkelen voor Azure Files met .NET
Leer de basisbeginselen van het ontwikkelen van .NET-toepassingen Azure Files gebruiken 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:
- Haal de inhoud van een bestand op.
- Stel de maximale grootte of het quotum voor een bestands share 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 bestands share.
- Een bestand herstellen vanuit een momentopname van een share.
- Gebruik Azure Storage metrics 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 |
|---|---|---|
| Standaardbestands shares (GPv2), LRS/ZRS | ||
| Standaardbestands shares (GPv2), GRS/GZRS | ||
| Premium (FileStorage), LRS/ZRS |
De .NET-API's
Azure Files biedt twee veelzijdige methoden voor het maken van clienttoepassingen: Server Message Block (SMB) en REST. Binnen .NET worden deze System.IO benaderingen door de Azure.Storage.Files.Shares API's en geabstraheerd.
| API | Wanneer gebruikt u dit? | Opmerkingen |
|---|---|---|
| System.IO | Uw toepassing:
|
Bestands-I/O die met een Azure Files via SMB is geïmplementeerd, is in het algemeen hetzelfde als I/O met een netwerkbestands share of een 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:
|
In dit artikel wordt het gebruik gedemonstreerd van Azure.Storage.Files.Shares voor bestands-I/O met behulp van REST in plaats van SMB en het beheer van de bestands share. |
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 ter vereenvoudiging een consoletoepassing.
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.
- Start Visual Studio en selecteer Een nieuw project maken.
- In Een nieuw project maken kiest u Console-app (.NET Framework) voor C# en selecteert u vervolgens Volgende.
- 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:
- Azure-kernbibliotheek voor .NET:dit pakket is de implementatie van de Azure-clientpijplijn.
- Azure Storage Blob-clientbibliotheek voor .NET:dit pakket biedt programmatische toegang tot blob-resources in uw opslagaccount.
- Azure Storage Files-clientbibliotheek voor .NET:dit pakket biedt programmatische toegang tot bestandsbronnen in uw opslagaccount.
- Systeembibliotheek Configuration Manager .NET:dit pakket biedt een klasse waarin waarden in een configuratiebestand worden opgeslagen en opgehaald.
U kunt NuGet gebruiken om de pakketten te verkrijgen. Volg deze stappen:
Klik Solution Explorer met de rechtermuisknop op uw project en kies NuGet-pakketten beheren.
Selecteer in NuGet Pakketbeheer de optie Bladeren. Zoek en kies vervolgens Azure.Core en selecteer installeren.
Met deze stap worden het pakket en de afhankelijkheden ervan geïnstalleerd.
Zoek en installeer deze pakketten:
- Azure. Storage. Blobs
- Azure. Storage. Files.Shares
- System.Configuration.ConfigurationManager
Sla uw opslagaccountreferenties op in het App.config bestand
Sla vervolgens uw referenties op in hetApp.configvan uw project. In Solution Explorer dubbelklikt u op het bestand en bewerkt u het zodat App.config het vergelijkbaar is met het volgende voorbeeld.
Vervang myaccount door de naam van uw opslagaccount en door de sleutel van uw mykey 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 te kunnen werken met Azure Files.
Using-instructies toevoegen
Open Solution Explorer het bestand Program.cs en voeg boven aan het bestand de volgende using-instructies toe.
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 bestands share.
Met de volgende methode maakt u een bestands share als deze nog niet bestaat. De methode begint met het maken van een ShareClient-object op connection string. Het voorbeeld probeert vervolgens een bestand te downloaden dat we eerder hebben 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 bestands share instellen. U kunt ook controleren hoeveel gegevens er momenteel zijn opgeslagen in de share.
Het instellen van het quotum voor een share beperkt de totale grootte van de bestanden die op de share zijn opgeslagen. Als de totale grootte van bestanden op de share het quotum overschrijdt, kunnen clients de grootte van bestaande bestanden niet verhogen. 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 SHARED Access Signature (SAS) genereren voor een bestands share of voor een afzonderlijk bestand.
De volgende voorbeeldmethode retourneert een SAS op 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 How a shared access signature works (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 een bestand naar een ander bestand 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 de kopie uit te voeren, omdat met deze bewerking bestanden binnen 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 de 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. Nadat de momentopnamen van de share 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 op een share vermeld.
//-------------------------------------------------
// 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 in momentopnamen van shares in een lijst bekijken
In het volgende voorbeeld worden bestanden en mappen in momentopnamen van shares gebladerd.
//-------------------------------------------------
// 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}");
}
}
}
Bestands shares of bestanden herstellen vanuit momentopnamen van shares
Door een momentopname van een bestands share te maken, kunt u afzonderlijke bestanden of de volledige bestands share herstellen.
U kunt een bestand vanuit een momentopname van de bestandsshare herstellen door de momentopnamen van shares van een bestandsshare op te vragen. Vervolgens kunt u een bestand ophalen dat bij een bepaalde momentopname van een share hoort. Gebruik deze 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 Storage Analytics ondersteunt metrische gegevens voor Azure Files. Met metrische gegevens kunt u aanvragen volgen en problemen diagnosticeren.
U kunt metrische gegevens voor Azure Files inschakelen vanuit Azure Portal. U kunt metrische gegevens ook programmatisch inschakelen door de bewerking Eigenschappen van bestandsservice instellen aan te roepen met de REST API of een van de analogen ervan in de Azure Files clientbibliotheek.
In het volgende codevoorbeeld ziet u hoe u de .NET-clientbibliotheek gebruikt om metrische gegevens in te 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 met Azure Files oplossen in Windows.
Volgende stappen
Zie de volgende bronnen Azure Files informatie over de gegevens: