This article outlines a set of functionalities for interacting with Azure Blob Storage using C#. A relevant code sample can be downloaded from GitHub by the Blob Storage

The HandleBlob class enables you to upload files to Azure Blob Storage and retrieve a list of blobs from a specific container. Designed for efficiency, the class supports advanced features like uploading large files in chunks and retrieving metadata about existing blobs.

Class Breakdown

Private Fields

private string _connectionString { get; set; }
private string _containerName { get; set; }
private string _blobName { get; set; }
private FileStream _fileStream { get; set; }

UploadFileToBlob() Method

This method uploads a file to Azure Blob Storage in chunks using the block blob storage model.

public async Task<Uri> UploadFileToBlob()
{
    Uri? blobUri = null;
    BlobServiceClient blobServiceClient = new BlobServiceClient(_connectionString);
    BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(_containerName);

    await containerClient.CreateIfNotExistsAsync();
    BlockBlobClient blockBlobClient = containerClient.GetBlockBlobClient(_blobName);

    using (FileStream fs = _fileStream)
    {
        long fileSize = fs.Length;
        int blockSize = 1 * 1024 * 1024;

        List<Task> uploadTasks = new List<Task>();
        int blockCount = (int)Math.Ceiling((double)fileSize / blockSize);
        byte[] buffer = new byte[blockSize];

        for (int i = 0; i < blockCount; i++)
        {
            int bytesRead = await fs.ReadAsync(buffer, 0, blockSize);
            byte[] blockData = buffer.Take(bytesRead).ToArray();
            string blockId = Convert.ToBase64String(BitConverter.GetBytes(i));
            uploadTasks.Add(blockBlobClient.StageBlockAsync(blockId, new MemoryStream(blockData)));
        }

        await Task.WhenAll(uploadTasks);
        List<string> blockIds = uploadTasks
            .Select(task => Convert.ToBase64String(BitConverter.GetBytes(uploadTasks.IndexOf(task))))
            .ToList();
        await blockBlobClient.CommitBlockListAsync(blockIds);

        blobUri = blockBlobClient.Uri;
    }
    return blobUri;
}

The method is asynchronous (async), and it returns a Uri pointing to the uploaded blob in Azure.

LoadAllBlobs() Method

This method asynchronously loads all the blobs in the specified container and returns a list of Blobs objects that contain metadata for each blob.

public async Task<List<Blobs>> LoadAllBlobs()
{
    BlobServiceClient blobServiceClient = new BlobServiceClient(_connectionString);
    BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(_containerName);
    List<Blobs> blobs = new List<Blobs>();

    await foreach (BlobItem blobItem in containerClient.GetBlobsAsync())
    {
        Blobs blob = new Blobs
        {
            name = blobItem.Name,
            blobUrl = containerClient.GetBlobClient(blobItem.Name).Uri.ToString(),
            dateModified = blobItem.Properties.LastModified?.DateTime ?? DateTime.MinValue
        };
        blobs.Add(blob);
    }
    return blobs;
}

Here’s how it works?

Key Components

Conclusion

The HandleBlob class provides a simple and efficient way to manage Azure Blob Storage operations such as uploading files in chunks and listing all blobs in a container.

It uses asynchronous methods to ensure non-blocking operations, making it suitable for production environments that require handling large files and high concurrency.