Dikembangkan untuk Azure Files dengan .Net

Pelajari dasar-dasar pengembangan aplikasi .NET yang menggunakan Azure Files untuk menyimpan data. Artikel ini memperlihatkan cara membuat aplikasi konsol sederhana untuk melakukan hal berikut dengan .NET dan Azure Files:

  • Dapatkan konten file.
  • Atur ukuran maksimum, atau kuota, untuk berbagi file.
  • Buat tanda tangan akses bersama (Shared Access Signature - SAS) untuk file.
  • Salin satu file ke satu file lain di akun penyimpanan yang sama.
  • Salin file ke blob di akun penyimpanan yang sama.
  • Buat salinan bayangan dari berbagi file.
  • Simpan ulang file dari salinan bayangan berbagi.
  • Gunakan Azure Storage Metrics untuk pemecahan masalah.

Untuk mempelajari Azure Files lebih lanjut, buka Apa itu Azure Files?

Tip

Lihat repositori contoh kode Azure Storage

Untuk contoh kode Azure Storage ujung ke ujung yang mudah digunakan yang dapat Anda unduh dan jalankan, lihat daftar Contoh Azure Storage kami.

Berlaku untuk

Jenis berbagi File SMB NFS
Berbagi file standar (GPv2), LRS/ZRS Ya Tidak
Berbagi file standar (GPv2), GRS/GZRS Ya Tidak
Berbagi file premium (FileStorage), LRS/ZRS Ya Tidak

Memahami .NET API

Azure Files menyediakan dua pendekatan luas untuk aplikasi klien: Server Message Block (SMB) dan REST. Di dalam .NET, System.IO dan Azure.Storage.Files.Shares API mengabstraksi pendekatan ini.

API Kapan saat menggunakan Catatan
System.IO Aplikasi Anda:
  • Perlu membaca/menulis file dengan menggunakan SMB
  • Sedang berjalan pada peranti yang memiliki akses melalui port 445 ke akun Azure Files Anda
  • Tidak perlu mengelola pengaturan administratif dari berbagi file
File I/O yang diimplementasikan dengan Azure Files melalui SMB umumnya sama dengan I/O dengan berbagi file jaringan atau peranti penyimpanan lokal. Untuk pengenalan sejumlah fitur di .NET, termasuk file I/O, lihat tutorial Aplikasi Konsol.
Azure.Storage.Files.Shares Aplikasi Anda:
  • Tidak dapat mengakses Azure Files dengan menggunakan SMB pada port 445 karena batasan firewall atau ISP
  • Memerlukan fungsionalitas administratif, misalnya kemampuan untuk mengatur kuota berbagi file atau membuat tanda tangan akses bersama
Artikel ini menunjukkan penggunaan Azure.Storage.Files.Shares untuk file I/O menggunakan REST dan bukannya SMB dan manajemen berbagi file.

Buat aplikasi konsol dan dapatkan rakitan

Anda dapat menggunakan pustaka klien Azure Files di dalam semua jenis aplikasi .NET. Aplikasi ini mencakup aplikasi cloud, internet, desktop, dan seluler Azure. Dalam panduan ini, kami menggunakan aplikasi konsol demi kesederhanaan.

Di Visual Studio, buat aplikasi konsol Windows yang baru. Langkah-langkah berikut menunjukkan bagaimana cara membuat aplikasi konsol di Visual Studio 2019. Langkah-langkah itu mirip pada versi Visual Studio lainnya.

  1. Mulai Visual Studio dan pilih Buat proyek baru.
  2. Di Buat proyek baru, pilih Aplikasi Konsol (.NET Framework) untuk C#, lalu pilih Berikutnya.
  3. Di Konfigurasikan proyek baruAnda, masukkan nama untuk aplikasi, dan pilih Buat.

Tambahkan semua contoh kode dalam artikel ini ke Program kelas dalam file Program.cs.

Gunakan NuGet untuk memasang paket yang diperlukan

Rujuk ke paket ini di proyek Anda:

Anda bisa menggunakan NuGet untuk mendapatkan paket. Ikuti langkah-langkah ini:

  1. Pada Penjelajah Solusi, klik kanan proyek Anda dan pilih Kelola Paket NuGet.

  2. Di Manajer Paket NuGet, pilih Jelajahi. Lalu cari dan pilih Azure.Core, lalu pilih Pasang.

    Langkah ini memasang paket dan dependensinya.

  3. Cari dan pasang paket ini:

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

Simpan kredensial akun penyimpanan Anda ke file App.config

Selanjutnya, simpan kredensial Anda di file App.config proyek Anda. Di Penjelajah Solusi, klik dua kali App.config dan edit file sehingga mirip dengan contoh berikut.

Ganti myaccount dengan nama akun penyimpanan Anda dan mykey dengan kunci akun penyimpanan Anda.

<?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>

Catatan

Azure Files saat ini tidak didukung oleh emulator penyimpanan Azurite. String koneksi Anda harus menargetkan akun penyimpanan Azure di cloud agar berfungsi dengan Azure Files.

Tambahkan menggunakan direktif

Di Penjelajah Solusi, buka file Program.cs, dan tambahkan yang berikut menggunakan direktif ke bagian atas file.

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;

Akses berbagi file secara terprogram

Dalam file Program.cs, tambahkan kode berikut untuk mengakses berbagi file secara terprogram.

Metode berikut ini membuat berbagi file jika belum ada. Metode ini dimulai dengan membuat objek ShareClient dari string koneksi. Sampel kemudian mencoba mengunduh file yang kita buat sebelumnya. Panggil metode ini dari 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");
    }
}

Atur ukuran maksimum untuk berbagi file

Mulai dari pustaka klien Azure Files versi 5.x, Anda dapat mengatur kuota (ukuran maksimum) untuk berbagi file. Anda juga dapat memeriksa untuk melihat berapa banyak data yang saat ini disimpan di berbagi.

Mengatur kuota untuk berbagi membatasi ukuran total file yang disimpan di berbagi. Jika ukuran total file pada berbagi lebih besar daripada kuota, klien tidak dapat meningkatkan ukuran file yang ada. Klien hanya dpat membuat file baru, jika file-file itu kosong.

Contoh di bawah ini menunjukkan cara memeriksa penggunaan saat ini untuk berbagi dan cara mengatur kuota untuk berbagi.

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

Buat tanda tangan akses bersama untuk file atau berbagi file

Dimulai dengan versi 5.x dari pustaka klien Azure Files, Anda dapat membuat tanda tangan akses bersama (SAS) untuk berbagi file atau untuk masing-masing file.

Metode contoh berikut ini memberi SAS pada file di berbagi yang ditentukan.

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

Untuk informasi selengkapnya mengenai membuat dan menggunakan tanda tangan akses bersama, lihat Cara kerja tanda tangan akses bersama.

Salin file

Dimulai dengan versi 5.x dari pustaka klien Azure Files, Anda dapat menyalin file ke file lain, file ke blob, atau blob ke file.

Anda juga dapat menggunakan AzCopy untuk menyalin satu file ke file lain atau menyalin blob ke file atau sebaliknya. Lihat Mulai menggunakan AzCopy.

Catatan

Jika Anda menyalin blob ke file, atau file ke blobn, Anda harus menggunakan tanda tangan akses bersama (SAS) untuk mengotorisasi akses ke objek sumber, bahkan jika Anda menyalin dalam akun penyimpanan yang sama.

Salin satu file ke satu file lain

Contoh berikut menyalin satu file ke satu file lain dalam berbagi yang sama. Anda dapat menggunakan autentikasi Shared Key untuk melakukan salinan karena operasi ini menyalin file dalam akun penyimpanan yang sama.

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

Salin file ke blob

Contoh berikut membuat file dan menyalinnya ke blob dalam akun penyimpanan yang sama. Contoh membuat suatu SAS untuk file sumber, yang digunakan layanan untuk mengotorisasi akses ke file sumber selama operasi salin.

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

Anda dapat menyalin blob ke file dengan cara yang sama. Jika objek sumber adalah blob, maka buat SAS untuk mengotorisasi akses ke blob itu selama operasi salin.

Salinan bayangan berbagi

Dimulai dengan versi 8.5 dari pustaka klien Azure Files, Anda dapat membuat salinan bayangan berbagi. Anda juga dapat mencantumkan atau menelusuri salinan bayangan berbagi dan menghapus salinan bayangan berbagi. Setelah dibuat, salinan bayangan berbagi bertuliskan baca-saja.

Buat salinan bayangan berbagi

Contoh berikut membuat salinan bayangan berbagi file.

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

Daftar salinan bayangan berbagi

Contoh berikut mencantumkan salinan bayangan pada suatu berbagi.

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

Daftar file dan direktori dalam salinan bayangan berbagi

Contoh berikut menelusuri file dan direktori dalam salinan bayangan bersama.

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

Simpan ulang bagi-pakai file atau file dari bagi-pakai salinan bayangan

Mengambil salinan bayangan dari berbagi file memungkinkan Anda memulihkan masing-masing file atau seluruh berbagi file.

Anda dapat memulihkan file dari salinan bayangan berbagi file dengan mengkueri salinan bayangan berbagi file. Anda kemudian dapat mengambil file milik salinan bayangan berbagi tertentu. Gunakan versi itu untuk membaca atau menyimpan ulang file secara langsung.

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

Hapus salinan bayangan berbagi

Contoh berikut menghapus salinan bayangan berbagi file.

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

Pemecahan masalah Azure Files menggunakan metriks

Azure Storage Analytics mendukung metrik Azure Files. Dengan data metrik, Anda dapat melacak permintaan dan mendiagnosis berbagai masalah.

Anda dapat mengaktifkan metrik untuk Azure Files dari portal Microsoft Azure. Anda juga dapat mengaktifkan metrik secara terprogram dengan memanggil Properti Layanan Set Fil dengan REST API atau salah satu analognya di pustaka klien Azure Files.

Contoh kode berikut menunjukkan bagaimana cara menggunakan pustaka klien .NET untuk mengaktifkan metrik untuk 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();
}

Jika Anda mengalami masalah, lihat Memecahkan masalah Azure Files.

Langkah berikutnya

Untuk informasi selengkapnya tentang Azure Files, lihat sumber daya berikut :

Artikel dan video konseptual

Dukungan alat untuk penyimpanan File

Referensi

Untuk sampel kode terkait menggunakan .NET versi 11.x SDK yang tidak digunakan lagi, lihat Sampel kode menggunakan .NET versi 11.x.