How Can I add a file to Azurite [Azure Storage Emulator]

Viewed 3442

I'm having a hard time figuring out how to add a file to this emulator in order to test azure blob different operations locally.

2 Answers

After you install azurite, you need to start it manually.

enter image description here

There are two ways to connect to Azurite:

1. enter image description here

2. enter image description here

enter image description here

The next step I think is the same as using azure storage in the cloud, only need to use sdk for blob operation:

var blobHost = Environment.GetEnvironmentVariable("AZURE_STORAGE_BLOB_HOST");  // 126.0.0.1:10000
var account = Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT"); // devstoreaccount1
var container = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONTAINER");
var emulator = account == "devstoreaccount1";
var blobBaseUri = $"https://{(emulator ? $"{blobHost}/{account}" : $"{account}.{blobHost}")}/";
var blobContainerUri = $"{blobBaseUri}{container}";

// Generate random string for blob content and file name
var content = Guid.NewGuid().ToString("n").Substring(0, 8);
var file = $"{content}.txt";

// With container uri and DefaultAzureCredential
// Since we are using the Azure Identity preview version, DefaultAzureCredential will use your Azure CLI token.
var client = new BlobContainerClient(new Uri(blobContainerUri), new DefaultAzureCredential());

// Create container
await client.CreateIfNotExistsAsync();

// Get content stream
using var stream = new MemoryStream(Encoding.ASCII.GetBytes(content));

// Upload blob
await client.UploadBlobAsync(file, stream);

You can refer to this official document, it has a more detailed tutorial. Or you can refer to this blog.

Related