Working With Azure Storage Account File Shares In C#

Working With Azure Storage Account File Shares In C#
Share:

About

In this code snippet, we will learn how to read, write and delete files to Azure File Shares using C#. Additionally, I’ll show you how to get the URL for a file and how to generate a SAS(shared access signature) token for it which can be used to download the file.

Note: You can use Azure Storage Explorer to inspect and edit file shares manually.

Let’s see how to use Azure File Shares with C# in the code examples below.

Prerequisites:

Before getting started you need to install the Azure File Shares client library NuGet package into your project: Azure.Storage.Files.Shares and add the following using statement at the top of your code file.
using Azure.Storage.Files.Shares;
using Azure.Storage.Files.Shares.Models;

Next, you need to get the connection string to your storage account. You can find it if you go to the storage account in the Azure portal and select “Access Keys”. We will need this in the code snippets below.

Note: It’s a good idea to save it as an environmental variable an not hardcode it as a string.

Code:

This code snippet demonstrates how to connect to your Azure storage account, create/select a file share, and upload a file.
private static async Task FileShareUpload()
{
    string connectionString = Environment.GetEnvironmentVariable("AzureWebJobsStorage");// "your_connection_string"; //Environment.GetEnvironmentVariable("AzureWebJobsStorage");
    string shareName = "test-share";
    string fileName = "test file.txt";



    //Create a ShareClient.
    ShareClient shareClient = new ShareClient(connectionString, shareName);
    //Create the file share if it doesn't exist already.
    await shareClient.CreateIfNotExistsAsync();
    //Get a reference to the directory.
    ShareDirectoryClient directoryClient = shareClient.GetRootDirectoryClient();
    //Creates or gets a reference to the specified file.
    ShareFileClient fileClient = directoryClient.GetFileClient(fileName);



    //Geta your data as a stream.
    using FileStream stream = File.OpenRead("C:\\Users\\DTPC\\Desktop\\"+ fileName);
    //or from byte[]
    //byte[] byteArray = File.ReadAllBytes(localFilePath); //your byte array
    //using MemoryStream stream = new MemoryStream(byteArray);

    //Create the file in the file share.
    await fileClient.CreateAsync(stream.Length);
    //Upload the file to file share.
    await fileClient.UploadRangeAsync(new HttpRange(0, stream.Length), stream);
}
This code snippet demonstrates how to read/delete a file in a file share and how to get data like the date of creation or the URL with a SAS(shared access token) for the file.
private static async Task FileShareDownload()
{
    string connectionString = Environment.GetEnvironmentVariable("AzureWebJobsStorage");// "your_connection_string"; //Environment.GetEnvironmentVariable("AzureWebJobsStorage");
    string shareName = "test-share";
    string fileName = "test file.txt";

    //Create a ShareClient.
    ShareClient shareClient = new ShareClient(connectionString, shareName);
    //Get a reference to the directory.
    ShareDirectoryClient directoryClient = shareClient.GetRootDirectoryClient();
    //Creates or gets a reference to the specified file.
    ShareFileClient fileClient = directoryClient.GetFileClient(fileName);
        
    //Download the file ...
    ShareFileDownloadInfo download = await fileClient.DownloadAsync();

    //This is how you can get the url.
    string uri = fileClient.Uri.AbsoluteUri;
    //To be able to access the file via the above url you have to also append a
    //SAS(shared access signiture) token with the appropriate permissions.
    string sasURI = fileClient.GenerateSasUri(Azure.Storage.Sas.ShareFileSasPermissions.Read, DateTimeOffset.Now.AddDays(1)).AbsoluteUri;

    Console.WriteLine(sasURI);

    //Example of some available metadata.
    Console.WriteLine(download.Details.LastModified);
    Console.WriteLine(download.Details.SmbProperties.FileCreatedOn);
    Console.WriteLine(download.ContentLength);


    //... and copy/open it as a stream.
    /*using (MemoryStream stream = new MemoryStream())
    {
        await download.Content.CopyToAsync(stream);

        //Do something with the stream ...
        //stream
    }*/

    //... or save it directly to a file using a file stream.
    using (FileStream stream = File.OpenWrite("C:\\Users\\DTPC\\Desktop\\downloaded.txt"))
    {
        //.. and copy/open it as a stream.
        await download.Content.CopyToAsync(stream);
    }

    //Delete the file.
    fileClient.DeleteIfExists();
}

Result:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger