C# — work with Azure BLOB storage files
Here are a few, short examples how to work with blobs in an Azure Storage Account.
You can check how to work with Data Lake Storage here: C# — work with Azure Data Lake storage files
At the beginning we need to add two packages:
- Azure.Storage.Blobs
- Azure.Identity
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Azure.Identity;
// dotnet add package Azure.Storage.Blobs
// dotnet add package Azure.Identity
Then, we create a Blob Service Client and a Blob Container Client. In this case a Service Principal is used to authenticate. AzureVariables is a separate static class where all fields are saved as strings.
// Create a BlobServiceClient
var credential = new ClientSecretCredential(AzureVariables.tenantId, AzureVariables.clientId, AzureVariables.clientSecret);
Uri blobEndpoint = new Uri(AzureVariables.blobEndpoint);
BlobServiceClient blobServiceClient = new BlobServiceClient(blobEndpoint, credential);
// Create a BlobContainerClient
string containerName = "iowa-json";
BlobContainerClient container = blobServiceClient.GetBlobContainerClient(containerName);
We are inside container, now we can do some file operations.
We can try to upload a file.
// Upload a file
// Specify a file to upload
string fileName00 = "05.json";
string fileToUpload = Path.Combine("json_files", fileName00);
// Create a BlobClient for the file
BlobClient blobClient00 = container.GetBlobClient(fileName00);
// Upload the file
var uploadBlob = await blobClient00.UploadAsync(fileToUpload, true);
System.Console.WriteLine($"Status: {uploadBlob.GetRawResponse().Status}, ReasonPhrase: {uploadBlob.GetRawResponse().ReasonPhrase}");
We can list files in the container.
// List files in a container
Azure.AsyncPageable<BlobItem> blobContainerList = container.GetBlobsAsync();
await foreach (BlobItem item in blobContainerList)
{
System.Console.WriteLine($"BLOB name: {item.Name}, Size: {item.Properties.ContentLength} bytes");
}
This code downloads a file to a local storage.
// Download a file from the container
// Create a BlobClient for the downloaded file
string fileName01 = "08.json";
BlobClient blobClient01 = container.GetBlobClient(fileName01);
// Specify a location for the downloaded file
string downloadFile = Path.Combine("json_Files", fileName01);
var downloadBlob = await blobClient01.DownloadToAsync(downloadFile);
This makes a file copy.
// Copy blob inside a container
BlobClient blobClient02_source = container.GetBlobClient(fileName01);
BlobClient blobClient02_destination = container.GetBlobClient("this_is_a_copy_" + fileName01);
await blobClient02_destination.StartCopyFromUriAsync(blobClient02_source.Uri);
We can remove a file this way.
// Remove the file
var removeBlob = await blobClient01.DeleteAsync();
Here is the code on GitHub