Working With Azure Storage Account Blobs In C#

Working With Azure Storage Account Blobs In C#
Share:

About

In this code snippet, we will learn how to read, write and delete files in Azure Blobs(binary large object) 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 Blobs with C# in the code examples below.

Prerequisites:

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

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 blob container, and upload a blob/file.
private static async Task BlobUpload()
{
    string connectionString = Environment.GetEnvironmentVariable("AzureWebJobsStorage");// "your_connection_string"; //Environment.GetEnvironmentVariable("AzureWebJobsStorage");
    string containerName = "test-container";
    string blobName = "test file.txt";



    //Create a BlobServiceClient.
    BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
    //Create a reference to the container.
    BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);
    //Create the blob container if it doesn't exist already.
    await containerClient.CreateIfNotExistsAsync();
    //Get reference to the blob.
    BlobClient blobClient = containerClient.GetBlobClient(blobName);



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

    //Upload the file to file share.
    await blobClient.UploadAsync(stream);
}
This code snippet demonstrates how to read/delete a file in a blob container and how to get the URL with a SAS(shared access token) for the blob file.
private static async Task BlobDownload()
{
    string connectionString = Environment.GetEnvironmentVariable("AzureWebJobsStorage");// "your_connection_string"; //Environment.GetEnvironmentVariable("AzureWebJobsStorage");
    string containerName = "test-container";
    string blobName = "test file.txt";

    //Create a BlobServiceClient.
    BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
    //Create a reference to the container.
    BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);
    //Get reference to the blob.
    BlobClient blobClient = containerClient.GetBlobClient(blobName);

    //Check if the blob exists.
    if (!blobClient.Exists())
    {
        Console.WriteLine("Blob doesn't exist.");
        return;
    }

    //This is how you can get the url.
    string uri = blobClient.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 = blobClient.GenerateSasUri(Azure.Storage.Sas.BlobSasPermissions.Read, DateTimeOffset.Now.AddDays(1)).AbsoluteUri;

    //Create "reference" to the blob.
    BlobDownloadInfo blobDownloadInfo = await blobClient.DownloadAsync();
    //Download blob and save it as a file stream.
    using (FileStream stream = File.OpenWrite("C:\\Users\\DTPC\\Desktop\\download.txt"))
    {
        await blobDownloadInfo.Content.CopyToAsync(stream);
    }

    //Delete the blob.
    blobClient.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