.NET sürüm 11.x istemci kitaplıklarını kullanan Azure Dosya Paylaşımı kod örnekleri

Bu makalede.NET için Azure Dosya Paylaşımı istemci kitaplığının 11.x sürümünü kullanan kod örnekleri gösterilmektedir.

31 Mart 2023'te , geçerli Azure SDK yönergelerine uymayan Azure SDK kitaplıkları desteğini kullanımdan kaldırdık. Yeni Azure SDK kitaplıkları, tutarlı deneyimler sağlamak ve güvenlik duruşunuzu güçlendirmek için düzenli olarak güncelleştirilir. Yeni özelliklerden ve kritik güvenlik güncelleştirmelerinden yararlanmak için yeni Azure SDK kitaplıklarına geçmeniz önerilir.

Eski kitaplıklar 31 Mart 2023'ten sonra da kullanılabilse de artık Microsoft'tan resmi destek ve güncelleştirme almayacaktır. Daha fazla bilgi için bkz. destek kullanımdan kaldırma duyurusu.

Önkoşullar

Bu paketleri proje dizininize yükleyin:

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

Aşağıdaki using yönergeleri ekleyin:

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

Dosya paylaşımına erişme

İlgili makale: .NET ile Azure Dosyalar için geliştirme

Dosya paylaşımına erişmek için aşağıdaki kodu ekleyin:

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

Dosya paylaşımı için boyut üst sınırını ayarlama

İlgili makale: .NET ile Azure Dosyalar için geliştirme

Azure Dosyalar istemci kitaplığının 5.x sürümünden başlayarak, dosya paylaşımı için kotayı (en büyük boyut) ayarlayabilirsiniz. Paylaşımda halihazırda ne kadar verinin depolandığını da kontrol edebilirsiniz.

Paylaşım kotasının ayarlanması, paylaşımda depolanan dosyaların toplam boyutunu sınırlar. Paylaşımdaki dosyaların toplam boyutu kotayı aşarsa, istemciler mevcut dosyaların boyutunu artıramaz. İstemciler, bu dosyalar boş olmadığı sürece yeni dosyalar da oluşturamaz.

Aşağıdaki örnekte, paylaşımdaki mevcut kullanımını nasıl kontrol edileceği veya paylaşım için nasıl kota ayarlanacağı gösterilmiştir.

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

Dosya veya dosya paylaşımı için paylaşılan erişim imzası oluşturma

Azure Dosyalar istemci kitaplığının 5.x sürümünden başlayarak, bir dosya paylaşımı veya tek bir dosya için paylaşılan erişim imzası (SAS) oluşturabilirsiniz.

Paylaşılan erişim imzalarını yönetmek için bir dosya paylaşımında depolanmış erişim ilkesi de oluşturabilirsiniz. Gizliliği tehlikeye girerse SAS'yi iptal etmenizi sağladığından, depolanmış erişim ilkesi oluşturmanızı öneririz. Aşağıdaki örnek, paylaşımda bir depolanmış erişim ilkesi oluşturur. Örnek, paylaşımdaki bir dosyada SAS kısıtlamalarını sağlamak için bu ilkeyi kullanır.

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

Dosyaları kopyalama

İlgili makale: .NET ile Azure Dosyalar için geliştirme

Azure Dosyalar istemci kitaplığının 5.x sürümünden başlayarak, bir dosyayı başka bir dosyaya, bir dosyayı bloba veya blobu bir dosyaya kopyalayabilirsiniz.

AzCopy'yi bir dosyayı başka bir dosyaya kopyalamak veya blobu bir dosyaya veya başka bir şekilde kopyalamak için de kullanabilirsiniz. Bkz. AzCopy ile çalışmaya başlama.

Not

Bir blobu dosyaya veya bir dosyayı bloba kopyalamak için aynı depolama hesabında kopyalama yapıyor olsanız da kaynak nesnesi erişimini yetkilendirmek amacıyla bir paylaşılan erişim imzası (SAS) kullanmanız gerekir.

Dosyayı başka bir dosyaya kopyalama

Aşağıdaki örnekte, bir dosya aynı paylaşımdaki başka bir dosyaya kopyalanır. Bu işlem aynı depolama hesabındaki dosyaları kopyaladığından, kopyayı yapmak için Paylaşılan Anahtar kimlik doğrulamasını kullanabilirsiniz.

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

Dosyayı bir bloba kopyalama

Aşağıdaki örnekte, bir dosya oluşturulur ve aynı depolama hesabındaki bir bloba kopyalanır. Örnekte, kaynak dosya için hizmetin kopyalama sırasında kaynak dosyaya erişimi yetkilendirmek üzere kullandığı bir SAS oluşturulur.

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

Aynı şekilde, bir blobu bir dosyaya kopyalayabilirsiniz. Kaynak dosya bir blob ise, kopyalama sırasında bu bloba erişimi yetkilendirmesi için bir SAS oluşturun.

Anlık görüntüleri paylaşma

İlgili makale: .NET ile Azure Dosyalar için geliştirme

Azure Dosyalar istemci kitaplığının 8.5 sürümünden başlayarak bir paylaşım anlık görüntüsü oluşturabilirsiniz. Ayrıca paylaşım anlık görüntülerini listeleyebilir, onlara göz atabilir ve paylaşım anlık görüntülerini silebilirsiniz. Oluşturulduktan sonra paylaşım anlık görüntüleri salt okunur olur.

Paylaşım anlık görüntüsü oluşturma

Aşağıdaki örnek bir dosya paylaşımı anlık görüntüsü oluşturur:

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

Paylaşım anlık görüntülerini listeleme

Aşağıdaki örnekte paylaşımdaki anlık görüntüler listelenir:

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

Paylaşım anlık görüntüleri içindeki dosyaları ve dizinleri listeleme

Aşağıdaki örnek, paylaşım anlık görüntüleri içindeki dosyalara ve dizinlere göz atar:

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

Paylaşım anlık görüntülerinden dosya paylaşımlarını veya dosyaları geri yükleme

Dosya paylaşımının anlık görüntüsünü almak, tek tek dosyaları veya dosya paylaşımının tamamını kurtarmanızı sağlar.

Bir dosya paylaşımının paylaşım anlık görüntülerini sorgulayarak bir dosya paylaşım anlık görüntüsündeki dosyayı geri yükleyebilirsiniz. Daha sonra belirli bir paylaşım anlık görüntüsüne ait olan bir dosyayı alabilirsiniz. Dosyayı doğrudan okumak veya geri yüklemek için bu sürümü kullanın.

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

Paylaşım anlık görüntülerini silme

Aşağıdaki örnek bir dosya paylaşımı anlık görüntüsünü siler:

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

Ölçümleri kullanarak Azure Dosyalar sorunlarını giderme

İlgili makale: .NET ile Azure Dosyalar için geliştirme

Azure Depolama Analizi Azure Dosyalar için ölçümleri destekler. Ölçüm verilerini kullanarak istekleri ve tanılama sorunlarını izleyebilirsiniz.

Azure portal Azure Dosyalar için ölçümleri etkinleştirebilirsiniz. Ayrıca REST API ile Dosya Hizmeti Özelliklerini Ayarla işlemini veya Azure Dosyalar istemci kitaplığındaki analoglarından birini çağırarak ölçümleri program aracılığıyla etkinleştirebilirsiniz.

Aşağıdaki kod örneği, Azure Dosyalar için ölçümleri etkinleştirmek üzere .NET istemci kitaplığının nasıl kullanılacağını gösterir.

İlk olarak, yukarıda eklediklerinizle birlikte Program.cs dosyanıza aşağıdaki using yönergeleri ekleyin:

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

Azure Blobları, Azure Tabloları ve Azure Kuyrukları ad alanında paylaşılan ServiceProperties türü kullansa da Microsoft.Azure.Storage.Shared.Protocol Azure Dosyalar ad alanındaki tür olan kendi türünü FileServicePropertiesMicrosoft.Azure.Storage.File.Protocol kullanır. Ancak aşağıdaki kodun derlenmiş olması için kodunuzdaki her iki ad alanına da başvurmanız gerekir.

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