Search code examples
azureazure-storageazure-cloud-servicesazure-storage-files

How to get lease on Azure storage file?


I have multi instance web application in azure cloud. I want to make sure that only one of them read and process file from azure storage file. I thought using lease option I can make it happen.

However I am unable to find proper methods for this operation. I found this REST API option but I am looking for something like this.

This example shows for blob storage. What are file storage options? I am using latest file storage nuget.

EDIT:

This is how I am getting data from storage file and processing the data.

    var storageAccount = CloudStorageAccount.Parse("FileStorageConnectionString");
    var fileClient = storageAccount.CreateCloudFileClient();
    var share = fileClient.GetShareReference("StorageFileShareName");
    var file = this.share.GetRootDirectoryReference().GetFileReference("file.txt");
---processing file and renaming the file after processing---

How to implement lease on this file so that no other cloud instance get the access to this file? After processing the file I will also rename it.


Solution

  • Please try something like below:

            string connectionString = "DefaultEndpointsProtocol=https;AccountName=<account-name>;AccountKey=<account-key>;EndpointSuffix=core.windows.net;";
            var shareClient = new ShareClient(connectionString, "test");
            shareClient.CreateIfNotExists();
            var fileClient = shareClient.GetRootDirectoryClient().GetFileClient("test.txt");
            var bytes = Encoding.UTF8.GetBytes("This is a test");
            fileClient.Create(bytes.Length);
            fileClient.Upload(new MemoryStream(bytes));
            var leaseClient = fileClient.GetShareLeaseClient();
            Console.WriteLine("Acquiring lease...");
            var leaseId = leaseClient.Acquire();
            Console.WriteLine("Lease Id: " + leaseId);
            Console.WriteLine("Breaking lease...");
            leaseClient.Break();
            Console.WriteLine("Lease broken...");
    

    It makes use of Azure.Storage.Files.Shares Nuget package.