Creating and uploading to specific folders in Azure Blob storage

Viewed 2970

I am trying to upload files to Azure blob storage via C# code, however, I need a specific directory tree. My code so far:

BlobServiceClient bSC = new BlobServiceClient(MY_CONN_STRING);

string filename = $"test/files/file.json";
string localFilePath = Path.Combine(filename);
var containerClient = bSC.GetBlobContainerClient("mycontainer");
BlobClient blobClient = containerClient.GetBlobClient(filename);

using FileStream uploadFileStream = File.OpenRead(localFilePath);
await blobClient.UploadAsync(uploadFileStream, true);
uploadFileStream.Close();

I have other piece of code that generates a file in test/files/file.json. In Azure blob storage, however, I want it to be uploaded to the directory tree of my choosing. Example: /mycontainer/Events/production/file.json, whever Events needs to be created as well. Right now it is recreating the tree structure within my project of test/files/file.json.

1 Answers

String parameter in GetBlobClient is responsible for "path" your file will have once uploaded, it should not be exactly the same as file name in your local system.

BlobClient blobClient = containerClient.GetBlobClient("mycontainer/Events/production/file.json");
Related